首页 新闻 会员 周边

代码效率的问题

0
悬赏园豆:10 [已解决问题] 解决于 2012-02-09 17:52
public static int ToInt(this string str, int defValue)
{
if (string.IsNullOrEmpty(str) || str.Trim().Length >= 11 ||
!Regex.IsMatch(str.Trim(), @"^([-]|[0-9])[0-9]*(\.\w*)?$"))
return defValue;

int rv;
if (Int32.TryParse(str, out rv))
return rv;

return  defValue;
}

 



public static int ToInt(this object obj, int defValue)
{
if (object.Equals(obj, null) || !Regex.IsMatch(obj.ToString().Trim(), @"^([-]|[0-9])[0-9]*(\.\w*)?$"))
return defValue;

int rv;
if (Int32.TryParse(obj.ToString(), out rv))
return rv;

return defValue;
}

这两个代码使用起来效率是不是一样的

问题补充: 呵呵,都对我的if有意见,那好吧,我把第一个if去掉,后面加try catch, 我用Stopwatch测试,object这个对象的时候效率高些
jhkmnm的主页 jhkmnm | 初学一级 | 园豆:19
提问于:2010-12-31 09:55
< >
分享
最佳答案
0

从绝对意义上来讲效率不一样。取决于执行逻辑、输入值等。
比较 object.Equals(object, null) 和 string.IsNullOrEmpty, object.Equals(object, object) 性能较差。
通过Reflector看反汇编:

[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public static bool Equals(object objA, object objB)
{
    return ((objA == objB) || (((objA != null) && (objB != null)) && objA.Equals(objB)));
}

如果用 obj == null 代替 object.Equals(object, null)则性能与string.IsNullOrEmpty相当。

假如用obj == null 直接比较,在 obj = string = "" 的情况下 (obj == null) 性能好于 string.IsNullOrEmpty(string). 原因不难理解,string.IsNullOrEmpty多了一个判断。

同样看一下string.IsNullOrEmpty反汇编的结果·
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public static bool IsNullOrEmpty(string value)
{
    if (value != null)
    {
        return (value.Length == 0);
    }
    return true;
}

it depends:)
 
有了TryParse 就用它吧~~

收获园豆:10
影猿帝(Ethan L.) | 菜鸟二级 |园豆:219 | 2011-01-03 20:59
其他回答(3)
0

把你第一个if删掉效率最高

Gray Zhang | 园豆:17610 (专家六级) | 2010-12-31 10:20
0

我想不通了。既然你已经知道TryParse这个函数了,干吗还加上那么多多余的?

顾晓北 | 园豆:10844 (专家六级) | 2010-12-31 11:58
0

就是啊,转化为整数就tryparse就可以了,连异常处理也可以不用加

Rain&Sun | 园豆:210 (菜鸟二级) | 2011-01-03 20:56
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册