JVM and CLR allocation optimization
Do the JVM and .NET VM allocate objects on the stack when it is obvious to the runtime that a开发者_StackOverflow社区n objects lifetime is limited to a certain scope?
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.
精彩评论