A deep dive into C++ singleton performance, comparing block-local static variables versus static data members, and user-declared versus user-defined constructors. When a user-defined constructor is required, the block-local static approach forces the compiler to insert guard variables and locking calls (__cxa_guard_acquire/__cxa_guard_release), adding overhead. Using a private static data member avoids these locks entirely. If the default constructor can be defaulted, both approaches produce equivalent assembly. The recommendation: use static data members when a custom constructor is needed, and block-local statics otherwise.

5m read timeFrom andreasfertig.com
Post cover image
Table of contents
Setting the sceneLet's talk performanceUsing a static data memeberSummary

Sort: