Best performance of a C++ singleton
andreasfertig.com
andreasfertig.com
The C++11 threadsafety guarantee on static initialization is explicitly scoped to block local statics. That's not an implementation detail, that's the guarantee.
The __cxa_guard_acquire/release machinery in the assembly is the standard fulfilling that contract. Move to a private static data member and you're outside that guarantee entirely. You've quietly handed that responsibility back to yourself.
Then there's the static initialization order fiasco, which is the whole reason the meyers singleton with a local static became canonical. Block local static initializes on first use, lazily, deterministically, thread safely. A static data member initializes at startup in an order that is undefined across translation units. If anything touches Instance() during its own static initialization from a different TU, you're in UB territory. The article doesn't mention this.
Real world singleton designs also need: deferred/configuration-driven initialization, optional instantiation, state recycling, controlled teardown. A block local static keeps those doors open. A static data member initializes unconditionally at startup, you've lost lazy-init, you've lost the option to not initialize it, and configuration based instantiation becomes awkward by design.
Honestly, if you're bottlenecking on singleton access, that's design smell worth addressing, not the guard variable.
There's a large group of engineers who are totally unaware of Amdahl's law and they are consequently obsessed with the performance implications of what are usually most non-important parts of the codebase.
I learned that being in the opposite group of people became (or maybe has been always) somewhat unpopular because it breaks many of the myths that we have been taught for years, and on top of which many people have built their careers. This article may or may not be an example of that. I am not reading too much into it but profiling and identifying the actual bottlenecks seems like a scarce skill nowadays.
I feel likethe mindset you are describing is kind of this intermediate senior level. Sadly a lot of programmers can get stuck there for their whole career. Even worse when they get promoted to staff/principal level and start spreading dogma.
I 100 percent agree. If you can't show me a real world performance difference you are just spinning your wheels and wasting time.
Many times taking a few extra ms, or God forbid 1s, is more than acceptable when there are humans in the loop.
I have to say that up until I grasped a pretty good understanding of CPU internals, memory subsystem, kernel, and generally the hardware, reading into the perf profiles was just a fun exercise giving me almost no meaningful results.
One of the reasons I hate constructors and destructors.
Explicit init()/deinit() functions are much better.
A bit like how java people insisted on making naive getFoo() and setFoo() to pretend that was different from making foo public
But it's absolutely different and sometimes it really matters.
I primarily work with C# which has the "property" member type which is essentially a first-class language feature for having a get and set method for a field on a type. What's nice about C# properties is that you don't have to manually create the backing field and implement the logic to get/set it, but you still have the option to do it at a later time if you want.
When you compile C# code (I expect Java is the essentially same) which accesses the member of another class, the generated IL/Bytecode is different depending on whether you're accessing a field, property or method.
This means that if you later find it would be useful to intercept gets or updates to a field and add some additional logic for some reason (e.g. you want to now do lazy initialization), if you naively change the field to a method/property (even with the same name), existing code compiled against your original class will now fail at runtime with something like a "member not found" exception. Consumers of your library will be forced to recompile their code against your latest version for things to work again.
By having getters and setters, you have the option of changing things without breaking existing consumers of your code. For certain libraries or platforms, this is the practical difference between being stuck with certain (now undesirable) behaviour forever or trivially being able to change it.
Recompiling isn't that hard usually.
These customers would also be quite rightfully annoyed when their devs report back to them that the extra work could have been entirely avoided if your own devs had done the industry norm of using setters/getters.
Maybe you're not a product but there are various other teams at your organization which use your library, now in order to go live you need to coordinate with various different teams that they also update their code so that things don't break. These teams will report to their PMs how this could have all been avoided if only you had used getters and setters, like the entire industry recommends.
Unless you're in a company with a single development team building a small system whose code would never be touched by anyone else, it's a good idea to do the setters/getters. And even then, what's true today might not be true years from now.
It's generally good practice for a reason.
Focusing on micro-"optimizations" like this one do absolutely nothing for performance (how many times are you actually calling Instance() per frame?) and skips over the absolutely-mandatory PROFILE BEFORE YOU OPTIMIZE rule.
If a coworker asked me to review this CL, my comment would be "Why are you wasting both my time and yours?"
In my view, the article is not about optimizing, but about understanding how things work under the hood. Which is interesting for some.
If a coworker submitted a patch to existing code, I'd be right there with you. If they submitted new code, and it just so happened to be using this more optimal strategy, I wouldn't blink twice before accepting it.
Other of us, use it as tool required to integrate with existing products, language runtimes, and SDKs written in C++, which most likely won't get replaced anytime soon.
Getting into the weeds of what a compiler does with your code is fun.
People have been doing micro optimisations since computers became a thing, you benefit from them every day without realising - and seemingly not appreciating - it.
https://compiler-explorer.com/z/Tsbz7nd44
This is about constant vs dynamic initialization, not trivial vs nontrivial default construction. To be fair, the article doesn't claim this, but that's the comparison being made.
The standard allows to optimize away dynamic initialization, but AFAIK there are ABI implications of doing that, so compilers tend to not do that.
If you absolutely want to guarantee that a global is constant initialized, use "constinit" on the variable declarations too. It can also have some positive codegen effects on declarations of thread_locals.
I ended up using std::call_once for those cases. More boilerplate but at least you're not debugging init order at 2am.
[0] https://stackoverflow.com/questions/51846894/what-is-the-per...
auto& s = DisplayManager::Instance();
s.SetResolution(Resolution::r640x480);
...just this: Display::SetResolution(Resolution::r640x480);
...since it's a singleton, the state only exists once anyway so there's no point in wrapping it in an object.E.g. what's the point of globally visible singletons except "everything is an object" cargo-culting?
Just put your state in an anonymous namespace in the implementation file.
> what's the point of globally visible singletons except "everything is an object" cargo-culting?
Having the singleton be an object becomes interesting when:
1) it contains attributes that themselves have non-trivial constructors and/or destructors. Order of initialization and destruction is guaranteed (init is in forward order of declaration, destruction in reverse order)
2) more rarely, inheritance (code reuse)
In the case of 1), you can just opt to construct the singleton on a sufficiently-aligned byte buffer in-place with `std::construct_at`. This gets rid of static-init order fiasco, __cxa bloat (if applicable), atexit bloat, and you can chose to just not call `std::destroy_at` if you don't need to.
In these two scenarios it's a lot more efficient to group many related objects into a bigger object.