Is access to a static function variable slower than access to a global variable?

  • A+
Category:Languages

Static local variables are initialised on the first function call:

Variables declared at block scope with the specifier static have static storage duration but are initialized the first time control passes through their declaration (unless their initialization is zero- or constant-initialization, which can be performed before the block is first entered). On all further calls, the declaration is skipped.

Also, in C++11 there are even more checks:

If multiple threads attempt to initialize the same static local variable concurrently, the initialization occurs exactly once (similar behavior can be obtained for arbitrary functions with std::call_once). Note: usual implementations of this feature use variants of the double-checked locking pattern, which reduces runtime overhead for already-initialized local statics to a single non-atomic boolean comparison. (since C++11)

At the same time, global variables seem to be initialised on program start (though technically only allocation/deallocation is mentioned on cppreference):

static storage duration. The storage for the object is allocated when the program begins and deallocated when the program ends. Only one instance of the object exists. All objects declared at namespace scope (including global namespace) have this storage duration, plus those declared with static or extern.

So given the following example:

struct A {     // complex type... }; const A& f() {     static A local{};     return local; }  A global{}; const A& g() {     return global; } 

am I correct to assume that f() has to check whether its variable was initialised every time it is called and thus f() will be slower than g()?

 


You are conceptually correct of course, but contemporary architectures can deal with this.

A modern compiler and architecture would arrange the pipeline such that the already-initialised branch was assumed. The overhead of initialisation would therefore incur an extra pipeline dump, that's all.

If you're in any doubt, check the assembly.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: