C#中判斷空字串的3種方法效能分析【月兒原創】
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.aspxprivate void Page_Load(object sender, System.EventArgs e) { string a=""; for(int i=0;i<=1000000;i++) { if(a=="")
WebForm2.aspxprivate 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)。