Thursday, November 12, 2009

Performance Issues When Comparing .NET Strings

Every time when you want to use string.Compare("str1", "str2", true) for case insensitive string comparison - think twice.

To illustrate my point I am bringing this example:

int iters = 100000;
string cmp1 = "SomeString";
string cmp2 = "Someotherstring";

Stopwatch sw = Stopwatch.StartNew();
for(int i =0 ;i < iters;i++)
    int res = string.Compare(cmp1, cmp2, true);

Console.WriteLine("First:" + sw.ElapsedMilliseconds);
sw = Stopwatch.StartNew();

for (int i = 0; i < iters; i++)
    int res = string.Compare(cmp1, cmp2, StringComparison.OrdinalIgnoreCase);

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

Quick question which method is faster, first or second?


Here is my result in milliseconds:

Wow, second sample nearly 3 times faster!!!
This is because first method uses culture-specific information to perform comparison, while the second uses ordinal compare method (compares numeric values of each char of the string).

Knowing the above we can deduce general rule of thumb: when culture-specific string comparison is not required we should use second way otherwise first one.

1 comment:

  1. Enjoy your Blog :)

    Click on the pub to :)hope you do te same

    Cheers from Portugal