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頁面(為什么用網(wǎng)頁,主要是利用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個壓力測試項目:

測試結(jié)果:
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頁面(為什么用網(wǎng)頁,主要是利用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個壓力測試項目:

測試結(jié)果:
WebForm1.aspx----------if(a=="")

WebForm2.aspx-------if(a==String.Empty)

WebForm3.aspx-------if(a.Length==0)

所以3種方法量化的結(jié)果是98,105,168:
方法 | 結(jié)果 |
if(a=="") | 98 |
if(a==String.Empty) | 105 |
if(a.Length==0) | 168 |
那么為什么if(a.Length==0)最快呢?
因為整數(shù)判斷等于最快,沒有經(jīng)過實例化等復雜的過程。
所以:建議大家判斷字符串是否為空用 if(a.Length==0)。
您可能感興趣的文章:
相關(guān)文章
文本框中輸入小寫字母即時轉(zhuǎn)換為大寫實現(xiàn)思路
系統(tǒng)中有一個文本框,要求輸入大寫字母,只是用戶不是那么配合所以只好在程序來控制了,感興趣的朋友可以參考下哈2013-03-03ASP.NET中MVC從后臺控制器傳遞數(shù)據(jù)到前臺視圖的方式
這篇文章主要介紹了ASP.NET中MVC從后臺控制器傳遞數(shù)據(jù)到前臺視圖的方式,以實例形式較為詳細的分析了asp.net中MVC數(shù)據(jù)傳遞的具體實現(xiàn)方法,需要的朋友可以參考下2014-12-12