String Comparison Performance

time to read 3 min | 437 words

During the Tel Aviv Launch I had an argument with Justin about the performance of string comparisons. The issue was whatever it is good to use str == "" or str.Length == 0, and the meriths of string.IsNullOrEmpty(str) in .Net 2.0.

Since Stefano just posted a comparison in VB.Net, I thought I would make the same check on C# (since VB.Net uses a compatability layer for string comparison). I merely ported Stefano's code:

DateTime start = DateTime.Now;
string str = "";
for (int i = 0; i < 1000000000; i++)
{
   if(str == "")
   // if (str.Length == 0)
   // if (str == string.Empty)
   // if (string.IsNullOrEmpty(str))
   {
      ;
   }
}
TimeSpan elapsed = DateTime.Now - start;
Console.WriteLine(elapsed.TotalMilliseconds);

The results?

str == "": 11671.875
str.Length == 0: 3984.375
str == string.Empty: 22265.625
string.IsNullOrEmpty(str): 9703.125

I'm not sure what is the reason for the big different between comparing to "" and comparing the string.Empty. An interesting experiment that I did gave the following result:

object

.ReferenceEquals("", str) is true

object

.ReferenceEquals(string.Empty, str) is false

No idea what this means, though.

From my point of view, if a billion iterations are needed to even see the changes, it doesn't matter which you choose anyway. Just to give you a hint, a call to str=="" will cost you 0.00001 milli-seconds. You'll need to find a physicist to tell you how to call this amount of time, and even then, he will look at you strangely ever after.