Reinventing The Wheel

Why do you have to initialise a local variable?

Have you ever wondered why instance fields don't have to be initialised and default to 0, false, null etc, while local variables have to be initialised before they can be used?

Turns out there are good reasons Microsoft made it this way. You get better performance, and better memory reuse.

Better Performance

When you create an instance of a class, it zeros the memory, providing the instance fields with default values. This takes time, and because in a method, there could be so many local variables, it would hurt performance to have to zero out the memory on the stack each time.

Instead, you are forced to initialise the local variable before you use it.

Memory Reuse

Another benefit of this is that the compiler can reuse memory slots.

If you have 3 for loops like this:

Once i becomes out of scope, j can use the same memory slot used by the variable i, and then when j becomes out of scope, k can then use that memory slot.

Because each local variable has to be initialised, the same memory slot can be reused without ever having to worry about what value is currently in there.