Why, in C++, do we prefer static initialization to dynamic initialization? Whats the big deal?if static initialization is so performant then why do new languages like Java, C# use dynamic initialization?
We don't. We prefer automatic initialisation - i.e. creating objects on the stack (as opposed to the heap). If we do that, their lifetimes are managed for us. This is one of many advantages that C++ has over Java. As to why Java works like this, you ought to ask the designers, but I'd guess that it is to simplify garbage collection (while introducing lots of other problems).
The main reason anyone even notices the difference in C++ is that static initialization cannot depend on the contents of other globals. Hence it doesn't run afoul of the initialization order fiasco.
So, if I'm going to have globals, I probably prefer them to be static-initialized, and then to fill in values in a controlled order, rather than take a chance on the order of dynamic initialization for objects not in the same translation unit. But actually, "we" (meaning I) prefer not to have globals at all in C++, and when we do have them "we" prefer them to be function-scope statics rather than global-scope statics. So it's a very mild preference indeed which way something is initialized that we don't want to exist in the first place.
Java does use analogues of static initialization for some things: final static integers are turned into compilation constants, even. But since in Java objects are always on the heap, and have user-defined constructors, objects can't be initialized with anything analogous to C++'s static initialization, which is done by the runtime before any user code is executed. Performance isn't a consideration when one of the two options is simply impossible in your language. Whenever a static field is initialized to null in Java, you might say that's analogous to C++ static initialization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With