Warren Falk

Singletons by delegate

Singletons are a common programming model, wherein a program ever only uses a single instance of a certain class, and that instance is shared program-wide.

The typical implementation of this is an if-null/lock/if-null setup that looks something like this:

class OnlyOne
{
  private OnlyOne _instance;
  public OnlyOne Instance
  {
    get
    {
      if (_instance == null)
      {
        lock (typeof(OnlyOne))
        {
          if (_instance == null)
          {
            _instance = new OnlyOne();
          }
        }
      }
      return _instance;
    }
  }
}

The reason for the if-null/lock/if-null is one for a different discussion, but it is basically the fastest portable way to allow thread-safe access to the single instance. However, it requires that the first if-null be executed every time a request for the instance is made. If your instance never changes, this is needless overhead.

I developed a quick and dirty solution using delegates. The basic idea is that when you create the first instance and you know it can no longer be null, you change the “GetInstance” routine to point to a routine that does not check for null. I created a generic for this. Here’s the result:

public class Singleton<T> where T: new()
{
  public delegate T InstanceGetter();

  private static T _instance;
  public static InstanceGetter GetInstance = new InstanceGetter(_GetNewInstance);
  private static T _GetNewInstance()
  {
    if (_instance == null)
    {
      lock (typeof(T))
      {
        if (_instance == null)
        {
          _instance = new T();
          GetInstance = new InstanceGetter(_GetInstance);
        }
      }
    }
    return _instance;
  }
  private static T _GetInstance() { return _instance; }
}

And then reusing it is quite easy:

class OnlyOne : Singleton<OnlyOne>
{
}

Now only the first call to OnlyOne.GetInstance() will actually check for null in a single threaded environment. And in the worst-case multithreaded environment, only the first simultaneous calls will check, the rest will just return the instance immediately.

My tests showed about a 25% performance gain. This is actually of questionable usefulness because you should not be calling the GetInstance method in a tight loop, you should call it once and assign it to a local. But I thought I’d share the basic idea because using delegates in this fashion might be useful in other scenarios.

2 Responses to “Singletons by delegate”

  1.  
    Thanks for the tips.  I often use delegates in that fasion but I am sure there are more senarios I could employ it in.
     
     
    By the way, I thought you would like this post on a blog I saw recently:
    http://languagelog.ldc.upenn.edu/nll/?p=295
     
     
     

  2. Make that, “Fashion”.

Leave a Reply

Not logged in: Log in

.
Entries (RSS) and Comments (RSS).