by Dominic Zukiewicz
3. July 2008 09:45
I don’t know about you, but when I’ve seen some string comparisons, some people use:
string text = GetStringFromDB()
if( text != string.Empty )
DoThis();
This looks good, but its actually quite a long running process, as the CLR has to compare both strings character by character. It is much better to use String.IsNullOrEmpty to cater for this, or use .Length == 0 property, as this never changes and is computed when assigned. Here is what the String.IsNullOrEmpty method looks like:
public static bool IsNullOrEmpty(string value)
{
if (value != null)
{
return (value.Length == 0);
}
return true;
}
If you use != , or ==, or .Equals() the method, it uses some hefty pointer manipulation like this:
public bool Equals(string value)
{
if ((value == null) && (this != null))
{
return false;
}
return EqualsHelper(this, value);
}
private static unsafe bool EqualsHelper(string strA, string strB)
{
int length = strA.Length;
if (length != strB.Length)
{
return false;
}
fixed (char* str = ((char*) strA))
{
char* chPtr = str;
fixed (char* str2 = ((char*) 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);
}
}
}
So in essence, don’t use != because
- It is massively slower
- It doesn’t take culture into consideration.
- It caters for 2 cases instead of 1 – what would you do if the string was null?