Singleton Pattern Performance Problem

I am looking at an existing piece of code that uses LOT of singleton classes and calls. I am trying to improve the performance of this code.

One thing that comes to mind is optimizing the Singleton :: getInstance () code snippet.

Instead of using Singleton :: getInstance (), I tend to replace this with a structure with two calls.

a. A function that will create and prepare an instance of singleton, for example Singleton :: prepareInstance (), which will be called once at the beginning of the subsystem. b. a built-in implementation of getInstance (), which simply returns the link without checking if it is valid or not.

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

Current Singleton :: getInstance () code, which looks like

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

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

+2
source share
3 answers

b. a built-in implementation of getInstance (), which simply returns the link without checking if it is valid or not.

Why is validity validated? My singleton implementations GetInstance()usually look like this:

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

I doubt that such code should have any impact on performance, and there is no need to verify anything for validity.

+6
source

Singleton::getInstance() . , ( singleton), , .

. getInstance(), , , .

, . Singleton::getInstance() .

+6

Use the profiler before performing the optimization. This usually shows where the execution time is running. In your case, this is most likely not the getInstance method for singletons, because they are likely to be inlined, and branch prediction will exclude the cost for the if-statement. If this proves to be a performance issue, it will be a good excuse to remove singlets and improve the architecture. If not, use the Meyer singleton (if multithreading is a problem, only for C ++ 11).

0
source

Source: https://habr.com/ru/post/1615207/


All Articles