Saturday, June 9, 2007

Use String.Compare -- sometimes

I recently came across this blog post on using String.Compare instead of the tried and true method of converting one string to lowercase and comparing to a known lower case value.  It's important to remember that strings in .NET (as in Java) are immutable so the act of lower casing a string will always make a new string.  The memory subsystem for .NET is turned for  handling lots of small objects but the fewer objects you create, the fewer that have to be checked and managed by the garbage collection system.

Still I wondered what the time difference would be between the two approaches.  So I setup a very simple test where I compared the string "FooBar" to a string variable that contained the value "foobar" one million times.  The first test used the approach of lowercasing the first string and then doing a simple equality comparison.  The average time spent for the entire loop was like .12 seconds.

The second comparison was to use String.Compare("FooBar", s, true) where s had the value "foobar" and true means to do a case insensitive comparison.  The average time spent in the loop was .10 seconds.  From this we can deduce that we should always use String.Compare right?  After all it's faster and definitely consumes less memory.  Well, not always.

My next test was a common scenario where you compare a value to a series of known values.  In this test, my input was the value "FooBar2" and I compared to "foobar", "foobar1", and "foobar2".  With the first test, I converted it to lower case just once and then did the comparisons using a series of if/else statements.  Time in the loop was .19 seconds.

The second test used String.Compare for each one of the if statements.  Time in the loop was .34 seconds.  So if you are doing a single string comparison, then String.Compare is your friend.  If you are doing a series of comparisons, then use a switch statement or the lowercase approach if speed is your concern.


  1. What about String.Equals(s1, s2, CultureInfo.InvariantCulture). How's that compare for speed? No new string allocation either.

  2. Not sure. Have not tried it. I'll try to think to do that, though.

  3. Hi nice site design