Strings in C#: == vs .Equals

I've heard a few times that .Equals is better than == for comparing strings in C#.  To test this, I wrote a little C# program that called == a hundred million times, and then compared it with .Equals.


Here's the code:


             string a = "hello";


             string b = "hello";


             int count = 0;


             DateTime start = DateTime.Now;


 


             for (int i=0; i<100000000; i++)


             {


                   if (a.Equals(b))


                         count++;


                   else


                         count++;


             };


 


             TimeSpan ts = DateTime.Now - start;


             Console.WriteLine("{0}", ts.Milliseconds);


The results were interesting.. I did the test four times, twice changing the strings so they were not equal (changing string “b” to “jello” from “hello”) and twice using == instead of .Equals.


Here's the results:

















 

a == b a.Equals(b)
Equal strings 961ms 655ms
Differing strings 750ms 890ms

So “a == b” is much slower when the strings are identical, and somewhat faster when the strings are different.  But either way, I could compare these strings a hundred million times in less than a second.  Another way to look at it is == is about 90% as fast as .Equals, on average (assuming your strings are the same about half the time).


Personally I think the difference is negligible and I prefer the readability of ==, but for performance-critical code it would make sense to think about whether you expect the strings to match or not match most of the time and choose the right one accordingly.