Not all string comparisons created equal

Not all string comparisons will perform the same but I was interested in seeing what exactly the differences were. Regardless of whether I was just performing 1 string comparison or 1 million, using the instance Equals() method was BY FAR the fastest. Of course the danger there is it will fail if the first string is null. Using == will always work regardless of nulls and for a million comparisons was almost as fast as Equals() and WAY faster than any other method (although it should be noted that using == is identical to using the static String.Equals() method). However, for 1 comparison it was by far the slowest. Note, for case-insensitive comparisons it is much faster to use the Compare() method with the case insensitive switch. Here are results below:


first == second -> 0.00021175875704873100
first.Equals(second) -> 0.0000086603185600445
(first.CompareTo(second) == -1) -> 0.00005531429273832290
(string.Compare(first, second) == -1) -> 0.00001396825574200070
string.Compare(first, second, true) == -1 -> 0.00001145396970844060
first.ToLower() == second.ToLower() -> 0.00002458413010592130

1,000,000 COMPARISONS:

first == second : 0.05631637540525400000   
first.Equals(second)  : 0.03321874707539650000   
(first.CompareTo(second) == -1) : 0.28999719238059600000   
(string.Compare(first, second) == -1) : 0.29059363690077900000   
string.Compare(first, second, true) == -1 : 0.30738375966777900000   
first.ToLower() == second.ToLower() : 0.77666714624344700000

Incidentally, a look at the instance Equals() method in Reflector:

    public extern bool Equals(string value);

Doing a million string comparisons in a loop might not be your common every day programming task and the timing difference will obviously not be perceptible to a human. But let's say you have a web page that does a single string comparison - if that page is accessed in a high volume environment (by thousands of browsers at once), then every little performance enhancement you can make is quite important.

Tweet Post Share Update Email RSS