Static local variables are initialised on the first function call:
Variables declared at block scope with the specifier static have static storage duratio
Yes, it is almost certainly slightly slower. Most of the time it will however not matter and the cost will be outweighted by the "logic and style" benefit.
Technically, a function-local static variable is the same as a global variable. Only just that its name is not globally known (which is a good thing), and its initialization is guaranteed to happen not only at an exactly specified time, but also only once, and threadsafe.
This means that a function-local static variable must know whether initialization has happened, and thus needs at least one extra memory access and one conditional jump that the global (in principle) doesn't need. An implemenation may do someting similar for globals, but it needs not (and usually doesn't).
Chances are good that the jump is predicted correctly in all cases but two. The first two calls are highly likely to be predicted wrong (usually jumps are by default assumed to be taken rather than not, wrong assumption on first call, and subsequent jumps are assumed to take the same path as the last one, again wrong). After that, you should be good to go, near 100% correct prediction.
But even a correctly predicted jump isn't free (the CPU can still only start a given number of instructions every cycle, even assuming they take zero time to complete), but it's not much. If the memory latency, which may be a couple of hundred cycles in the worst case can be successfully hidden, the cost almost disappears in pipelining. Also, every access fetches an extra cacheline that wouldn't otherwise be needed (the has-been-initialized flag likely isn't stored in the same cache line as the data). Thus, you have slightly worse L1 performance (L2 should be big enough so you can say "yeah, so what").
It also needs to actually perform something once and threadsafe that the global (in principle) doesn't have to do, at least not in a way that you see. An implementation can do something different, but most just initialize globals before main
is entered, and not rarely most of it is done with a memset
or implicitly because the variable is stored in a segment that is zeroed anyway.
Your static variable must be initialized when the initialization code is executed, and it must happen in a threadsafe manner. Depending on how much your implementation sucks this can be quite expensive. I decided to forfeit on the thread safety feature and always compile with fno-threadsafe-statics
(even if this isn't standard-compliant) after discovering that GCC (which is otherwise an OK allround compiler) would actually lock a mutex for every static initialization.