正文

C#中判断空字符串的3种方法性能分析2007-04-28 16:03:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/Csharpsky/25293.html

分享到:

C#中判断空字符串的3种方法性能分析

 3种方法分别是:
string a="";
1.if(a=="")
2.if(a==String.Empty)
3.if(a.Length==0)

3种方法都是等效的,那么究竟那一种方法性能最高呢?本人用实验说明问题。

建立3aspx页面(为什么用网页,主要是利用Microsoft Application Center Test

WebForm1.aspx
private void Page_Load(object sender, System.EventArgs e)
  {   string a="";
   for(int i=0;i<=1000000;i++)
   {    if(a=="")    {    }   }
  }

WebForm2.aspx
private void Page_Load(object sender, System.EventArgs e)
  {
   string a="";
   for(int i=0;i<=1000000;i++)
   {    if(a==String.Empty)    {    }   }
  }

WebForm3.aspx
private void Page_Load(object sender, System.EventArgs e)
  {   string a="";
   for(int i=0;i<=1000000;i++)
   {    if(a.Length==0)    {    }   }
  }

 Microsoft Application Center Test 下建立3个压力测试项目:

测试结果:

WebForm1.aspx----------if(a=="")
WebForm2.aspx-------if(a==String.Empty)
WebForm3.aspx-------if(a.Length==0)

所以3种方法量化的结果是98105168

方法

结果

if(a=="")

98

if(a==String.Empty)

105

if(a.Length==0)

168

那么为什么if(a.Length==0)最快呢?
因为整数判断等于最快,没有经过实例化等复杂的过程。

所以:建议大家判断字符串是否为空用 if(a.Length==0)

对于三种方法的评价:

1.if(a=="") // ""
需要实例化一个String对象,最差
2.if(a==String.Empty) // String.Empty
是常量,不需要实例化
3.if(a.Length==0) // a.Length
虽然最快,但是语意不如第2种清晰

,String.IsNullOrEmpty(value)判断的是该字符串是非为空,或者为空字符串.

结论:推荐使用2.if(a==String.Empty),安全,稳定,语意清晰.

 

阅读(4924) | 评论(1)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

loading...
您需要登录后才能评论,请 登录 或者 注册