Skip to content

Does Java’s new keyword necessarily denote heap allocation?

I’m trying to write something fast, and that constantly allocates and deallocates memory, making where this memory is allocated important in terms of performance.

Does allocating objects always allocate them to the heap? Does JIT compilation do fancy allocation optimization of any sort?



Objects allocated with new are placed on the heap, but the JIT/JVM might optimize them to stack using escape analysis. Read more about it in this article published on IBM developerWorks:

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

You have no possibility to directly control stack allocation, in the same way you cannot predict when the GC will be run. If you really need such a deep control over memory mechanisms, the only way is using C/C++.

Anyway, think twice before overcomplicating your piece of software. The conclusion of the paper I linked above is quite clear about memory management:

JVMs are surprisingly good at figuring out things that we used to assume only the developer could know. By letting the JVM choose between stack allocation and heap allocation on a case-by-case basis, we can get the performance benefits of stack allocation without making the programmer agonize over whether to allocate on the stack or on the heap.

Which does not mean that you will never ever need a fine-grained control over memory, but that in most cases a JVM can optimize better than an average programmer.