Search code examples
c++optimizationc++17singletonstatic-initialization

Minimizing Meyers' singleton overhead


Meyers singleton, s. t.:

Foo& getSingleton() {
    static Foo singleton;
    return singleton;
}

Is known to be:

  • Thread-safe.
  • Have a branch(es?) inside.

And it also happens to be the easiest way to avoid static initialization order fiasco.

But, if I'm executing in single-threaded environment, its thread-safety (which can't be disabled via default language means) might be critical to performance.

What are the ways industry uses to get rid of extra atomic flag for Meyers singleton and minimize branches.


Solution

  • For gcc, clang, and msvc there are specific commandline options to turn off thread safety for static variables [1][2][3].

    That beeing said, before using these flags (basically switching to non-C++-standard-mode) one should have carefully measured and identified the synchronization on the singleton as a hotspot optimization opportunity.

    [1] https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Dialect-Options.html#index-fno-threadsafe-statics
    [2] https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fthreadsafe-statics
    [3] https://learn.microsoft.com/en-us/cpp/build/reference/zc-threadsafeinit-thread-safe-local-static-initialization