As far as I know the JVM uses escape analysis for some performance optimisations like lock coarsening and lock elision. I'm interested if there is a possibility for the JVM to decide that any particular object can be allocated on stack using escape analysis.
Some resources make me think that I am right. Is there JVMs that actually do it?
With this version of java -XX:+DoEscapeAnalysis results in far less gc activity and 14x faster execution.
Without escape analysis,
With escape analysis,
The execution time reduces significantly with escape analysis. For this the loop was changed to 10e9 iterations,
Without escape analysis,
With escape analysis,
So with escape analysis the example ran about 14x faster than the non-escape analysis run.
Escape analysis is really nice, but it is not a complete get of jail free card. if you have a dynamically sized collection inside of an object, the escape analysis will NOT switch from heap to stack. For example:
Even if this object is created in a method and absolutely does NOT escape from a syntactic point of view, the compiler will not mark this for escape. I suspect because that longList is not really bounded in size from a pure syntactic perspective and it could blow your stack potentially. Thus I believe it takes a pass on this case. I experimented with this where the longList was empty and still it caused collections in a simple micro benchmark.
I don't think it does escape analysis for stack allocation. example:
with
-server -verbose:gc -XX+DoEscapeAnalysis
:Allegedly JDK 7 supports stack allocation.