In C++, what is the expected runtime cost in a reasonable compiler of initializing a static variable with a variable value as opposed to a constant value?
For example consider this code:
bool foo();
bool baz1() {
const bool value = foo();
static bool alternate1 = value;
static bool alternate2 = false;
// Do something.
return alternate1;
}
What is the expected run-time cost difference between alternate1 and alternate2?
Initialisation from a compile-time constant (alternate 2) will most likely happen during program startup, with no cost each time the function is called.
Thread-safe initialisation of a local static variable will cause the compiler to generate something like this pseudocode:
So there is likely to be a test of a flag each time the function is called (perhaps involving a memory barrier or other synchronisation primitive), and a further cost of acquiring and releasing a lock the first time.
Note that in your code,
foo()is called every time, whether or not the variable is initialised yet. It would only be called the first time, if you changed the initialisation toThe details are implementation-dependent of course; this is based on my observations of the code produced by GCC.