String.Equals Performance Comparison

I recently had an app that I used the VSTS Profiler on to find that a significant portion of time was spent comparing some long strings.  I was using String.Equals(string a, string b, StringComparison.InvariantCultureIgnoreCase) since I didn't care about case or culture.  I switched to using OrdinalIgnoreCase and got a huge 5x performance gain!  So that begged the question, just how long do the various string comparison algorithms comparatively take?

OrdinalIgnoreCase was the fastest. Ordinal was almost 2x as long. The others were about 5x the cost.

The "==" operator ("a" == "b") uses Ordinal by default.  So if case sensitivity isn't an issue, you can get a 2x performance gain by using OrdinalIgnoreCase.

To perform the calculation: Comparing strings 200 characters in length made up of random characters 4,000,000 times with each of the StringComparison values, all done 4 times and averaged.  On a 1.8GHz Dell D610 w/ 2GB RAM using .NET 3.5 Beta2.  Download StringComparisonTest.zip

References

Comments

  • Anonymous
    June 29, 2007
    In previous versions, string.Compare(string, string, bool) could be used to perform case-insensitive comparisons. The MSDN docs for that method state: "The comparison uses the current culture to obtain culture-specific information such as casing rules and the alphabetic order of individual characters. " Underneath the covers, what is the string-string-bool method doing? Does it map itself to one of the StringComparison enums?

  • Anonymous
    July 08, 2007
    I looked at the code using Reflector: public static int Compare(string strA, string strB, bool ignoreCase) {    if (ignoreCase)    {        return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase);    }    return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.None); }

  • Anonymous
    July 11, 2007
    Anthony Borton on Can't delete files from Document Library. Noad Coad on String.Equals Performance Comparison....

  • Anonymous
    July 21, 2008
    I ran some similar tests at http://akutz.wordpress.com/2008/07/20/stringing-along-in-net/

  • Anonymous
    July 28, 2008
    The comment has been removed

  • Anonymous
    December 05, 2008
    you should call duration.TotalMilliseconds instead of duration.Milliseconds, it returns wrong result!!! so the optimal comparison method is ordinal

  • Anonymous
    June 26, 2009
    Your test are for long strings.  I am doing some heavy comparision with short strings and they are numbers (as string). So I will try with the OrdinalIgnoreCase. Do you have any comments about performance of string comparision with short strings ?

  • Anonymous
    August 11, 2010
    Are the results still valid for .NET 4.0?