For years I’ve been comparing strings by converting them to lower case to avoid pesky users who have a habit of using upper and lower case letters. You know the sort of thing:

bool res = s1.ToLower() == s2.ToLower();

But it turns out that my code is horribly slow, or at least it could be a lot faster. Because after all C# is pretty fast in comparison to many other languages.

I saw a post online about this and thought I’d test it out for myself. The Class below is the result:

    public class StringCompareTest
    {
        public static void CompareStrings(int n)
        {
            String s1 = "Hello";
            String s2 = "World";
            Stopwatch sw = Stopwatch.StartNew();
            for (int i = 0; i < n; i++)
            {
                bool res = String.Equals(s1, s2, StringComparison.OrdinalIgnoreCase);
            }
            sw.Stop();

            Console.WriteLine("String.Equals: " + sw.ElapsedMilliseconds);

            sw.Reset();
            sw.Start();
            for (int i = 0; i < n; i++)
            {
                bool res = s1.ToLower() == s2.ToLower();
            }
            sw.Stop();

            Console.WriteLine("ToLower()    : " + sw.ElapsedMilliseconds);

            sw.Reset();
            sw.Start();
            for (int i = 0; i < n; i++)
            {
                bool res = false;
            }
            sw.Stop();

            Console.WriteLine("NOP          : " + sw.ElapsedMilliseconds);

        }
    }

Which was run with this line in the main program:

StringCompareTest.CompareStrings(10000000);

There are three tests, one using ToLower(), one using the String.Equals function and one that I’ve referred to as NOP (No Operation) to highlight any latency cause by the code which runs the tests.

Here are the results for 10 million operations, in milliseconds:

Test 1

String.Equals: 66
ToLower()    : 478
NOP          : 6

Test 2

String.Equals: 53
ToLower()    : 491
NOP          : 7

As you can see the loop and assignment of a value to the bool within it runs in 6-7 ms, so the difference in performance between ToLower() and String.Equals is:

472 / 62 = 7.61

Or in the second example:

486 / 46 = 10.52

For one operation that’s not a huge improvement but in a loop where you’re performing multiple operations perhaps thousands of times it’s well worth remembering.

Leave a Reply

Your email address will not be published. Required fields are marked *