古詩詞大全網 - 成語經典 - C#中怎麽判斷空字符

C#中怎麽判斷空字符

C#判斷空字符串的三種方法,這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

privatevoidPage_Load(objectsender,System.EventArgse)

{

stringa="";

for(inti=0;i=1000000;i++)

{

if(a=="")

{

}

}

}

WebForm2.aspx

privatevoidPage_Load(objectsender,System.EventArgse)

{

stringa="";

for(inti=0;i=1000000;i++)

{

if(a==String.Empty)

{

}

}

}

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)。