首页 > Web开发 > 详细

asp.ent(C#)中判断空字符串的3种方法以及性能分析

时间:2016-01-31 07:47:53      阅读:136      评论:0      收藏:0      [点我收藏+]
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)。

asp.ent(C#)中判断空字符串的3种方法以及性能分析

原文:http://www.jb51.net/article/21145.htm

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!