Tag Archives: stringcomparison

Best Practices for String Comparison

I was interested in the efficiency of string comparison. For example, when performing a case-insensitive comparison, is it better to use the String.Equals method with StringComparison.InvariantCultureIgnoreCase, or the simple trick of converting both strings to upper- or lower-case? I found an MSDN article, New Recommendations for Using Strings in Microsoft .NET 2.0, that discusses all this and more.

In a nutshell:

  • Use an overload that takes the StringComparison enumeration
  • If you don’t care about the linguistic content, as in the majority of cases, use StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase for the best performance. An ordinal comparison runs the fastest because it compares bytes directly and applies no linguistic rule to compute the result.

Going back to my original question, using String.InvariantCultureIgnoreCase is not as efficient because while it specifies culture-independence, the strings are still compared in a linguistic sense. And when you normalize casing with String.ToUpperInvariant or String.ToLowerInvariant, the extra step means that the comparison is not as fast as using StringComparison.OrdinalIgnoreCase.