3種方法分別是:string a="";1.if(a=="")2.if(a==String.Empty)3.if(a.Length==0)
3種方法都是等效的,那么究竟那一種方法性能最高呢?本人用實驗說明問題。
建立3個aspx頁面(為什么用網頁,主要是利用Microsoft application Center Test)
WebForm1.aspxPRivate 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.aspxprivate 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)。
新聞熱點
疑難解答