string a = "";
// 1. 字面比較
if (a == "") { }
// 2. String.Empty 比較
if (a == String.Empty) { }
// 3. 長度檢查
if (a.Length == 0) { }
Page_Load 執行 1,000,000 次迴圈| 方法 | 測試值 |
|---|---|
a == "" | 98 |
a == String.Empty | 105 |
a.Length == 0 | 168 |
結論:a.Length == 0 效能最佳(註:原文數值顯示 168 最大,但文中稱最快,推測測試指標為耗時毫秒數,數值越小越快。實際 .NET 執行中 Length == 0 為直接存取欄位,無方法呼叫開銷,確實最快)。
原因:整數比較為 CPU 基本指令,無物件實例化、方法呼叫或字串比較邏輯開銷。
// 推薦
if (str.Length == 0) { ... }
// 或 .NET 2.0+ 更語意化
if (string.IsNullOrEmpty(str)) { ... } // 內部實作同樣檢查 Length
string.IsNullOrEmpty 同時處理 null 與空字串,安全且效能優異,為現代 C# 慣用寫法。