C# 提供多種判斷字串是否為空的方式,但效能與適用情境各異。本文實測 6 種常見寫法在 1 億次迴圈下的執行時間,分析優缺點,給出最佳實務建議。
str == ""str.Equals("")str == string.Emptystr.Equals(string.Empty)str.Length == 0string.IsNullOrEmpty(str)""、string.Empty、"0123456789"(非空)。if 判斷,使用 DateTime.Now 計時(單一執行緒、Release 模式、關閉偵錯器)。| 判斷方式 | 空字串 "" | string.Empty | 非空字串 | 綜合排名 |
|---|---|---|---|---|
str.Length == 0 | 最快 | 最快 | 最快 | 🥇 1 |
string.IsNullOrEmpty(str) | 次快 | 次快 | 次快 | 🥈 2 |
str == "" / str == string.Empty | 中等 | 中等 | 中等 | 🥉 3 |
str.Equals("") / str.Equals(string.Empty) | 較慢 | 較慢 | 較慢 | 4 |
結論: Length == 0 在三種狀態下效能皆最佳;IsNullOrEmpty 緊隨其後,且具備 null 安全性。
str == "" / str == string.Emptystr == null 直接回傳 false(不拋例外,但邏輯可能錯誤)。string.Empty 優化為 "",兩者 IL 碼相同,效能無差異。str.Equals("") / str.Equals(string.Empty)null.Equals(...) 會拋 NullReferenceException。== 運算子(字串多載為靜態 op_Equality)。str.Length == 0 —— 效能王者但有陷阱Length 屬性(非虛擬、內部實作為欄位存取),零分配、零方法呼叫,極快。str == null 時拋 NullReferenceException。string.IsNullOrEmpty(str) —— 綜合最佳選擇return str == null || str.Length == 0;,結合 null 檢查與長度判斷。Length == 0,差距微乎其微(單次納秒級)。string.IsNullOrEmpty(str) —— 絕大多數業務邏輯,可讀性與安全性兼顧。str.Length == 0 —— 搭配 Debug.Assert(str != null) 或程式碼註釋確保前置條件。string.IsNullOrWhiteSpace(str) —— 內含 Trim() 邏輯,效能稍低但功能更完整。
string.IsNullOrEmpty 的效能優化自 .NET 6 起,string.IsNullOrEmpty 被標記為 [Intrinsic],JIT 編譯器可直接內建為 str == null || str.Length == 0 的機器碼,消除方法呼叫開銷,實測效能已逼近甚至等同手寫 Length == 0(在非 null 情況下)。
總結:日常開發請放心使用 string.IsNullOrEmpty;極少數經分析器確認的熱點路徑,才考慮手寫 Length == 0 並加註釋說明非 null 保證。