Sunday, September 9, 2012

C# Case Insensitive String Comparison

The .NET framework gives us two easy ways to check whether two strings are equal or not ignoring their case. The first way is to convert each string to lower case using the String.ToLower or the faster String.ToLowerInvariant method and then compare the strings with the "==" operator and the second way is to to use the String.Equals method specifying an ordinal ignore case string comparison type. Both methods will get the job done, but have you ever wondered which one is faster?

Let's use our C# algorithms performance test class to find out:

class StringComparisonTest : PerformanceTest
{
    public StringComparisonTest()
        : base("ToLowerInvariant comparison", "OrdinalIgnoreCase comparison")
    {
    }

    public override void Method1()
    {
        for (int i = 0; i < ComparisonCount; i++)
        {
            if (String1.ToLowerInvariant() == String2.ToLowerInvariant())
            {
                DoNothing();
            }
        }
    }

    public override void Method2()
    {
        for (int i = 0; i < ComparisonCount; i++)
        {
            if (String.Equals(String1, String2,
                StringComparison.OrdinalIgnoreCase))
            {
                DoNothing();
            }
        }
    }

    private const int ComparisonCount = 500 * 1000;
    private const string String1 = "Test";
    private const string String2 = "tesT";
}

Let's run the test:

PerformanceTest test = new StringComparisonTest();
string results = test.Execute();

Console.WriteLine("\n==============================");
Console.WriteLine(results);
Console.WriteLine("==============================\n");

On my machine I get the following result:

==============================
 ToLowerInvariant comparison = 14601 ms
OrdinalIgnoreCase comparison =  1530 ms
------------------------------
OrdinalIgnoreCase comparison is 854,31 % faster
==============================

The conclusion is that checking whether two strings are case insensitively equal using an ordinal ignore case string comparison is more than 9 times faster than converting the two strings to lower case and comparing them using the "==" operator.

See also:

No comments:

Post a Comment