The statement does or does not make sense depending on how you punctuate it:
Reading 1:
The advantage of static data is that it can be initialized to desired values before the program starts. The disadvantage is that the memory space is occupied throughout the whole program execution, even if the variable is only used in a small part of the program.
All of the above makes data caching less efficient.
This is nonsense.
Reading 2:
The advantage of static data is that it can be initialized to desired values before the program starts.
The disadvantage is that the memory space is occupied throughout the whole program execution...
...even if the variable is only used in a small part of the program. There is a case where this could make data caching less efficient.
That case would be where the static variable has been allocated storage either in a page that is not always swapped in, or is on a cache line that is rarely otherwise used. You may incur a cache miss, or theoretically in the worst case a page fault (although frankly, with the amount of physical memory at our disposal these days, if this happens you have bigger problems).
In the specific case you demonstrate, the answer would be, "it depends".
Yes, the initialisation of static_arr
is a one-time-only operation and so can be thought of as costless.
Yes, the initialisation of local_arr
happens each time the function is called, but it might be that:
- this initialisation is trivial, or
- the initialisation is elided by the compiler as part of an optimiser pass
In general, unless you have a specific optimisation in mind, it is Better(tm) to write the code that explicitly states the behaviour you want, i.e.:
use static variables (variables with static storage duration) when the variable/array's value(s) should survive successive calls to the function.
use local variables (strictly, variables with automatic storage duration) when the existing values are meaningless on entry or exit from the function.
You will find that the compiler will in almost all cases, do the most efficient thing after the optimisation pass(es).
There is a specific case case where static initialisation is Better(tm). In the case of (say) a buffer that requires dynamic allocation. You may not want to incur the cost of allocation/deallocation on every call. You may want the buffer to dynamically grow when needed, and stay grown on the basis that future operations may well need the memory again.
In this case, the actual state of the variable is the size of its allocated buffer. Thus, state is important on the function's entry and exit, eg:
std::string const& to_string(json const& json_object)
{
static thread_local buffer; // thread-safe, auto-expanding buffer storage
buffer.clear(); // does not release memory
serialise_to_string(buffer, json_object); // may allocate memory occasionally
return buffer;
}