Dot Net Perls

Singleton Performance Benchmarks - C#

by Sam Allen

Problem

Benchmark singletons. You require a singleton pattern that is both thread-safe and very fast. Eliminate compiler-generated baggage in your singleton code. Use Jon Skeet's singleton descriptions and determine the easiest and fastest version.

Solution: C#

Singletons are wonderful for when you need to restrict an object to one instance. In many projects, they are accessed thousands of times and sometimes very frequently. The cost of accessing the singleton structure is very tiny.

Why optimize it? Because even tiny improvements matter. My investigation here also helps us understand how the C# compiler works to generate code. Essentially, I compare public fields and properties here.

Which singletons? Carefully read Jon Skeet's Implementing the Singleton article. As the author says, version 4 is as fast as any option. Here it is.

class SingletonA
{
    static readonly SingletonA _instance = new SingletonA();
    public static SingletonA Instance
    {
        get
        {
            return _instance;
        }
    }
    public void Test()
    {
        // Code runs.
    }

    SingletonA()
    {
    }
}
//
// Access with:
// SingletonA.Instance.Test();
//

How fast? In one million iterations of the Test function in the above version, the program completed in 1.935 seconds. That is very efficient.

Using public fields

The above code block shows the singleton is using a property to be accessed. Jon Skeet notes that properties are inlined by the C# compiler. However, my testing shows that by exchanging the property for a public field, the benchmark is sped up.

class SingletonB
{
    public static readonly SingletonB _instance = new SingletonB();

    public void Test()
    {
        // Code runs.
    }

    SingletonB()
    {
    }
}
//
// Access with:
// SingletonB._instance.Test();
//

Benchmark results

We're looking at very tiny amounts of time here, but I don't see any reason why you shouldn't use the faster version if they are identical, which Jon indicates. Don't expect this to make your program as fast as Google Chrome!

What we see. The times for the benchmark of 1 billion iterations was 1.935 seconds versus 1.731 seconds (in Release mode). Clearly, using the public field (in the second example) is faster. Using properties slows down singletons.

Discussion

Both singleton versions here are identical in normal situations. However, the public field is over 10% faster. I recommend skipping the public property as shown first and simply using the field. Both versions are tested by Jon according to his article linked above.

Dot Net Perls
About
Sitemap
Source code
RSS
Language Features
Struct Examples and Tricks
Run Commands With Process.Start
Singleton Pattern vs. Static Class
NGEN Installer Class
Enum Tips and Examples
Recent
Pi
NGEN Installer Class
List Element Equality
DateTime Tips and Tricks
Remove HTML Tags From String
© 2008 Sam Allen. All rights reserved.