Does the singleton pattern in C++ have processor overhead? If it does, how much?
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
//...
int main() {
// Assume singleton is initialized;
Singleton::getInstance().var;
}
I'm specifically asking about overhead cost of access compared to, for example;
int main() {
// Singleton is a namespace;
Singleton::var;
}
The Scott Mayor singleton (former function local static object) is protected against multiple initializations via a hidden std::once_flag
and a std::call_once
.
This, in effect, means that there's a static memory overhead of sizeof(std::once_flag)
, and one conditional branch over the state of std::once_flag
upon each call to the function. The operations on std::once_flag
are atomic, but it only affects concurrent calls on the uninitialized object (the first time). And sizeof(std::once_flag)
is typically that of an integral type (less than 8).
If the program is probably strictly single threaded, the costs of atomic operations may be totally removed, but the std::once_flag
will still remain as an indicator of first or subsequent calls to the function.