在C#中可以使用3種方法來判斷字符串是否為空字符串,具體為:
string a="";
(1)if(a=="")
(2)if(a==String.Empty)
(3)if(a.Length==0)
上面三種方法都是等效的,但究竟那一種方法性能較好呢?下面通過實驗來說明。
建立3個aspx頁面(為什么用網(wǎng)頁,主要是利用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個壓力測試項目:
測試結(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)過實例化等復(fù)雜的過程。
所以:建議大家判斷字符串是否為空用 if(a.Length==0)。
新聞熱點(diǎn)
疑難解答