Is this multithreaded Singleton more efficient?

Viewed 439

I have a high-throughput Singleton in a multithreaded environment. Usually I'd do something like this:

public static Foo GetInstance()
{
    lock (Foo._syncLock)
    {
        if (Foo._instance == null)
            Foo._instance = new Foo();
        return Foo._instance;
    }
}

I'm wondering if doing the following instead would be more efficient since it would avoid the continual thread locking, or are there hidden problems with it?

public static Foo GetInstance()
{
    if (Foo._instance != null)
        return Foo._instance;
    lock (Foo._syncLock)
    {
        if (Foo._instance == null)
            Foo._instance = new Foo();
        return Foo._instance;
    }
}
2 Answers
Related