views:

116

answers:

1

Do the JVM and .NET VM allocate objects on the stack when it is obvious to the runtime that an objects lifetime is limited to a certain scope?

+3  A: 

The JVM does this. It can actually remove the allocation totally, under the right circumstances.

Quoting this article.

The Java language does not offer any way to explicitly allocate an object on the stack, but this fact doesn't prevent JVMs from still using stack allocation where appropriate. JVMs can use a technique called escape analysis, by which they can tell that certain objects remain confined to a single thread for their entire lifetime, and that lifetime is bounded by the lifetime of a given stack frame. Such objects can be safely allocated on the stack instead of the heap. Even better, for small objects, the JVM can optimize away the allocation entirely and simply hoist the object's fields into registers.

More information on Escape analysis from Wikipedia.

Steve K