tags:

views:

426

answers:

4

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?

+2  A: 

In general, we prefer neither static nor dynamic init. Determining which one is preferred for a particular situation depends on your particular situation.

John Dibling
+8  A: 

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).

anon
+1 for the crucial stack vs heap distinction. I've tweaked your answer ever so slightly, but please revert if you don't like it.
Draemon
Newer versions of the JVM can allow allocation to the stack instead of the heap with the -server -XX:+DoEscapeAnalysis option. When it is possible to do this optimization, this can provide some major improvements in performance. Hopefully this will be enabled by default in Java7
Steve g
A: 

Who says we do? Honestly it's the first time I hear something like this.. Static initialization is better in some contexts, while dynamic is better in others. The rule of thumb is: if you know at compile time how big / how many then use static (easier, faster to type, no need to use smart pointers / delete, no memory leaks).. Otherwise you have no choice but to use dynamic.

Andreas Bonini
+3  A: 

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.

Steve Jessop