remudada
remudada

Reputation: 3791

Singleton Pattern performance issue

I am reviewing an existing piece of code which uses a LOT of singleton classes and accesses. I am trying to improve the performance of this code.

One thing that comes to mind is to optimize the Singleton::getInstance() piece of code.

Rather than using Singleton::getInstance(), I am inclined to replace this with structure with two calls.

a. A function that would create and prepare the singleton instance, like Singleton::prepareInstance() that would be called once at the start of the subsystem. b. an inline implementation of getInstance() that would just return the reference without checking if it's valid or not.

Is that a viable solution? Any way to improve on this?

The current Singleton::getInstance() code that I have looks like this

Singleton * Singleton::getInstance() {
    if(m_instance == NULL) {
        m_instance = new Singleton();
    }
    return m_instance;
}

Is the approach mentioned by πάντα ῥεῖ any faster?

Upvotes: 3

Views: 2583

Answers (3)

Jens
Jens

Reputation: 9406

Use a profiler before you do optimization. It is usually quite revealing where the runtime is spent. In your case, it is very likely not the getInstance method of the singletons, because these will probably be inlined and branch prediction will eliminate the cost for the if-statement. If it turns out to be a performance issue, this will be a good excuse to remove the singletons and improve the architecture. If not, use Meyer's singleton (if multi-threading is a concern, only for C++11).

Upvotes: 0

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

b. an inline implementation of getInstance() that would just return the reference without checking if it's valid or not.

Why there's need to check for validity? My singleton GetInstance() implementations usually look like this:

Singleton& Singleton::instance() {
    static Singleton theInstance;
    return theInstance;
}

I doubt such code should have any performance impact, neither it's necessary to check anything for validity.

Upvotes: 9

Lea Hayes
Lea Hayes

Reputation: 64206

A proper implementation of Singleton::getInstance() shouldn't have any performance issues. Sure the first invocation might be costly (for the initial setup of the singleton instance) but any subsequent invocations should simply return the instance which should be super fast.

b. an inline implementation of getInstance() that would just return the reference without checking if it's valid or not.

In my view this goes against one of the fundamental concepts of the singleton pattern. Singleton::getInstance() should ALWAYS return a valid instance.

Upvotes: 7

Related Questions