緣起於 FxCop 建議使用 string.Length 判斷空字串,本文探討背後原因。
bool isEmpty = (str.Length == 0);bool isEmpty = (str == String.Empty);bool isEmpty = (str == "");透過 Reflector 反編譯 System.String 原始碼片段:
public sealed class String : IComparable, ICloneable, ... {
static String() { string.Empty = ""; }
public static readonly string Empty;
public static bool Operator ==(string a, string b) { return string.Equals(a, b); }
public static bool Equals(string a, string b) {
if (a == b) return true;
if ((a != null) && (b != null)) return string.EqualsHelper(a, b);
return false;
}
private static unsafe bool EqualsHelper(string ao, string bo) {
int num1 = ao.Length;
if (num1 != bo.Length) return false;
// 逐字元比較...
}
private extern int InternalLength();
public int Length { get { return this.InternalLength(); } }
}
Rotor 版本類似,但無 EqualsHelper,改用 public extern bool Equals(String value);。
下篇將詳細比較三種寫法的效能差異。