This is a very simple question:
Does 0-initializing global and static variables have any performance penalty (albeit very small) at runtime?
This is a very simple question:
Does 0-initializing global and static variables have any performance penalty (albeit very small) at runtime?
No, since the C++ (and C) standard says that all global/static variables that are not initialized explicitly by the programmer, must be initialized to zero. Such variables are placed in a special segment called .bss
. They are initialized to zero before main() is called.
If you initialize your global/static explicitly, but to the value 0, the compiler is smart enough to realize this and still put it in the bss
segment.
You can test this for yourself with an example like this:
#include <stdio.h>
static int uninit;
static int init_zero=0;
static int init_one=1;
int main (void)
{
printf("%p\n", &uninit);
printf("%p\n", &init_zero);
printf("%p\n", &init_one);
return 0;
}
In this example, the uninit
and init_zero
variables will end up at adjacent memory addresses (likely 4 bytes away from each other), since they are both in the .bss
segment. But the init_one
variable will end up somewhere else entirely, because it is allocated in the .data
segment.
Extending the question from 0-initialization (which is just a subset of) to default initialization, we still can conclude that it usually has no measurable impact on application performance. However, it is easy to design a class which will do, for example, database lookup in it's constructor - thus leading for interesting effects noticeable during application startup.