asp.ent(C#)中判断空字符串的3种方法以及性能分析
更新时间:2009年11月28日 02:20:36 作者:
asp.ent(C#)中判断空字符串的3种方法以及性能分析
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)
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.NET从1.0到4.0的OutputCache Bug介绍
一个伴随ASP.NET从1.0到4.0的OutputCache Bug介绍,学习.net的朋友可以参考下。2011-11-11Entity Framework使用Code First模式管理数据库
本文详细讲解了Entity Framework使用Code First模式管理数据库的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2022-03-03ASP.NET Core 6.0 基于模型验证的数据验证功能
这篇文章主要介绍了ASP.NET Core 6.0 基于模型验证的数据验证,本文描述的数据验证方案,是基于官方的模型验证(Model validation),需要的朋友可以参考下2022-07-07asp.net javascript 文件无刷新上传实例代码
最近在写C# .net代码的时候,遇到一个上传刷新的问题。2009-06-06
最新评论