Choosing the best way to compare text to empty strings

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

  1. It is massively slower
  2. It doesn’t take culture into consideration.
  3. It caters for 2 cases instead of 1 – what would you do if the string was null?

Tags:

Framework | Good practices

Powered by BlogEngine.NET 1.5.0.7
Theme by Interakting

Interakting

A full service digital agency offering online strategy, design and usability, systems integration and online marketing services that deliver real business benefits and ensure your online objectives are met.

Calendar

<<  March 2010  >>
MoTuWeThFrSaSu
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar