三種方法分別是:
string a = "";
1. if (a == "")
2. if (a == String.Empty)
3. if (a.Length == 0)
三種方法都等效,那麼究竟哪種效能最高?筆者用實驗說明。
建立三個 ASPX 頁面(為什麼用網頁,主要是利用 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 下建立三個壓力測試專案。
測試結果:
WebForm1.aspx ---------- if (a == "")
WebForm2.aspx ------- if (a == String.Empty)
WebForm3.aspx ------- if (a.Length == 0)
三種方法量化結果為 98、105、168:
| 方法 | 結果 |
|---|---|
| if (a == "") | 98 |
| if (a == String.Empty) | 105 |
| if (a.Length == 0) | 168 |
為什麼 if (a.Length == 0) 最快?因為整數判斷等於最快,沒有經過實例化等複雜過程。
建議大家判斷字串是否為空用 if (a.Length == 0)。