public sealed class String : IComparable, ICloneable, IConvertible, IEnumerable, IComparable<string> ...{ static String() ...{ string.Empty = ""; // Code here } // Code here 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) ...{ // Code here int num1 = ao.Length; if (num1 != bo.Length) ...{ return false; } // Code here } private extern int InternalLength(); public int Length ...{ get ...{ return this.InternalLength(); } } // Code here }
Rotor里面String類的代碼與此沒(méi)什么不同,只是沒(méi)有EqualsHelper方法,代之以如下的聲明: public extern bool Equals(String value); 進(jìn)一步分析: 首先是Empty法,由于String.Empty是一個(gè)靜態(tài)只讀域,只會(huì)被創(chuàng)建一次(在靜態(tài)構(gòu)造函數(shù)中)。但當(dāng)我們使用Empty法進(jìn)行判空時(shí),.NET還會(huì)依次展開(kāi)調(diào)用以下的方法,而后兩個(gè)方法內(nèi)部還會(huì)進(jìn)行對(duì)象引用判等! public static bool operator ==(string a, string b); public static bool Equals(string a, string b); private static unsafe bool EqualsHelper(string ao, string bo); 若使用General法判等的話,情況就“更勝一籌”了!因?yàn)?NET除了要依次展開(kāi)調(diào)用上面三個(gè)方法之外,還得首先創(chuàng)建一個(gè)臨時(shí)的空字符串實(shí)例,如果你要進(jìn)行大量的比較,這恐怕是想一想就很?chē)樔肆耍?BR>而對(duì)于Length法,我們就可以繞過(guò)上面這些繁瑣的步驟,直接進(jìn)行整數(shù)(字符串長(zhǎng)度)判等,我們知道,大多數(shù)情況下,整數(shù)判等都要來(lái)得快(我實(shí)在想不出比它更快的了,在32位系統(tǒng)上,System.Int32運(yùn)算最快了)! 另外,我們還可以看到,在EqualsHelper方法里面.NET會(huì)先使用Length法來(lái)進(jìn)行判等!可惜的是我無(wú)法獲得InternalLength方法的代碼。但我在Mono的源代碼里面看到更簡(jiǎn)明的實(shí)現(xiàn):