| LingKai's profileRomance Dawn 冒险开始的地方PhotosBlogLists | Help |
|
29 January [技术帖]随便写点什么吧 1承认我是比较无聊。。。。
开个头吧
一个被人鄙视的小问题 -- C#中,如何判断字符串是空字符串呢。。。。?
string.IsNullOrEmpty?
string.Compare / string.CompareTo ?
string.Equals / string == "" ?
各有什么区别?
================================================================================
以下是CLR中的实现
public static int CompareTo(string s1, string s2)
{ return System.Globalization.CultureInfo.CurrentCulture.CompareInfo.Compare(s1, s2, System.Globalization.CompareOptions.None); } public static bool IsNullOrEmpty(string value)
{ if (value != null) { return (value.Length == 0); } return true; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] private static unsafe bool EqualsHelper(string strA, string strB) { int length = strA.Length; if (length != strB.Length) { return false; } fixed (char* str = strA)
{ char* chPtr = str; fixed (char* str2 = strB) { char* chPtr2 = str2; char* chPtr3 = chPtr; char* chPtr4 = chPtr2; while (length >= 10) { if ((((*(((int*)chPtr3)) != *(((int*)chPtr4))) || (*(((int*)(chPtr3 + 2))) != *(((int*)(chPtr4 + 2))))) || ((*(((int*)(chPtr3 + 4))) != *(((int*)(chPtr4 + 4)))) || (*(((int*)(chPtr3 + 6))) != *(((int*)(chPtr4 + 6)))))) || (*(((int*)(chPtr3 + 8))) != *(((int*)(chPtr4 + 8))))) { break; } chPtr3 += 10; chPtr4 += 10; length -= 10; } while (length > 0) { if (*(((int*)chPtr3)) != *(((int*)chPtr4))) { break; } chPtr3 += 2; chPtr4 += 2; length -= 2; } return (length <= 0); } } } ====================================================================
IsNullOrEmpty是最直接的
==相当于调用重载了的Equals, 对于string来说是Equals(string)。从上面reflection出来的片断可以理解成以10字节为一大步,2字节为一小步的比较。(为什么这个组合performance最好?)
最本质的区别在于,CompareTo是culture sensitive的。它会根据当前的culture info,对字符串中的字符取权值,然后计算比较。(非顺序比较) |
|
|