Reputation: 386
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?
Upvotes: 4
Views: 1303
Reputation: 33046
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.
Upvotes: 11
Reputation: 718688
The JLS says that new
allocates a new object. JLS 12.5:
"A new class instance is explicitly created when evaluation of a class instance creation expression (§15.9) causes a class to be instantiated."
The JLS doesn't say where an object is allocated. If the compiler can infer (via escape analysis) that the reachability rules allow an object to be allocated on the stack, then that is permitted.
The JLS is generally read as permitting optimizations whose effect cannot be detected by observing the result of executing a program. Apparently, the most recent versions of Java 7, one of the optimizations that is performed involves optimizing away exception create / throw / catch code and replacing it with an unconditional jump statement (or similar ...). In some cases, this optimization involves optimizing away an explicit new
statement.
In summary, a new
expression normally results in a heap allocation, but sometimes the object is allocated on the stack, and sometimes the allocation is optimized away entirely.
Upvotes: 2