您的位置:首页 > 编程语言 > C#

C#判断字符串为空的3种方法性能测试

2010-01-04 11:36 323 查看
文章导读:C#中判断空字符串的3种方法性能分析,有图有真相。

Backli:来源网络,供大家参考学习~

3种方法分别是:

string a="";

1.if(a=="")

2.if(a==String.Empty)

3.if(a.Length==0)

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

建立3个aspx页面(为什么用网页,主要是利用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种方法量化的结果是98,105,168:

方法结果
if(a=="")98
if(a==String.Empty)105
if(a.Length==0)168
那么为什么if(a.Length==0)最快呢?

因为整数判断等于最快,没有经过实例化等复杂的过程。

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

转自:http://enzit.cn/boke/?action=show&id=151
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: