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:

I: 113
S: 100

I: 144
S: 96

I: 126
S: 89

I: 126
S: 94

I: 128
S: 97

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.

Tags: , , , ,

2 Responses to “Static vs Instance string.Equals Benchmark”

  1. Chris L. says :

    Speed is one measure. What about the memory footprint? (probably not significant with a small string though)

    • David Haney says :

      The strings in this case are literals and thus interned, which helps with the memory if the strings were repeated. I believe that both methods, assuming that they function identically, use the same amount of stack and possibly heap memory.

Leave a Reply

Your email address will not be published. Required fields are marked *