- ·上一篇内容:Visual Foxpro应用程序的开发步骤
- ·下一篇内容:优酷超G文件上传方法
C#中判断空字符串的方法
在C#中可以使用3种方法来判断字符串是否为空字符串,具体为:
string a="";
(1)if(a=="")
(2)if(a==String.Empty)
(3)if(a.Length==0)
上面三种方法都是等效的,但究竟那一种方法性能较好呢?下面通过实验来说明。
建立3个aspx页面(为什么用网页,主要是利用Microsoft Application Center Test )
(1)WebForm1.aspx
privatevoidPage_Load(objectsender,System.EventArgse)
{
stringa="";
for(inti=0;i<=1000000;i++)
{
if(a=="")
{
}
}
}
(2)WebForm2.aspx
privatevoidPage_Load(objectsender,System.EventArgse)
{
stringa="";
for(inti=0;i<=1000000;i++)
{
if(a==String.Empty)
{
}
}
}
(3)WebForm3.aspx
privatevoidPage_Load(objectsender,System.EventArgse)
{
stringa="";
for(inti=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)。
本文源自:翔宇亭——IT乐园(http://www.biye5u.com),转载请保留此信息!
微信搜索“优雅的代码”关注本站的公众号,或直接使用微信扫描下面二维码关注本站公众号,以获取最新内容。
个人成长离不开各位的关注,你的关注就是我继续前行的动力。