Static vs Instance string.Equals Benchmark

A friend of mine commented on my last post asking about how much faster the static string.Equals method is than the instance string.Equals method. To satiate both of our curiosities, I have created this benchmarking application:

static void Main(string[] args)
{
    var stopwatch = new Stopwatch();

    string a = "hello";
    string b = "hi";

    stopwatch.Start();
    for (int i = 0; i < 10000000; i++)
    {
        a.Equals(b);
    }
    stopwatch.Stop();

    Console.WriteLine("Instance string.Equals over 10,000,000 iterations: " 
	    + stopwatch.ElapsedMilliseconds + " ms");

    stopwatch.Reset();

    stopwatch.Start();
    for (int i = 0; i < 10000000; i++)
    {
        string.Equals(a, b);
    }
    stopwatch.Stop();

    Console.WriteLine("Static string.Equals over 10,000,000 iterations: "
	    + stopwatch.ElapsedMilliseconds + " ms");

    Console.ReadKey();
}

The results of 5 runs, where “I” is the instance method and “S” is the static method, and the times are in milliseconds:

Instance Static
113ms 100ms
144ms 96ms
126ms 89ms
126ms 94ms
128ms 97ms

And there you have it. Static string.Equals is reliably slightly faster… But unless you’re doing millions of comparisons, it probably doesn’t really matter much. It does, however, prevent the NullReferenceException mentioned in the last post when the string instance is null.


See also