What is Escape Analysis and Scalar Replacement
π§ 1. What is Escape Analysis?
Escape Analysis asks a simple question:
β Does this object “escape” the method? (i.e., is it used outside the current method?)
- If yes β the object must go on the heap.
- If no β the object can stay in a local variable (i.e., on the stack or just in registers).
π§ͺ Example: No Escape
public int compute() {
Point p = new Point(5, 10);
return p.x + p.y;
}
Here:
p
is only used insidecompute()
.- It does not escape β so JVM doesnβt need to allocate
Point
on heap.
Graal JIT detects this and eliminates the object allocation entirely!
β 2. What is Scalar Replacement?
Once Graal knows an object doesn’t escape, it can break the object into its parts (its scalars) and use them directly, without creating the object at all.
Continuing the same example:
Point p = new Point(5, 10);
int result = p.x + p.y;
Graal JIT will do this:
int x = 5;
int y = 10;
int result = x + y;
No
Point
object is created. It just usesx
andy
β this is scalar replacement.
π« What if object does escape?
public Point compute() {
Point p = new Point(5, 10);
return p; // Escapes the method
}
- Now
p
escapes (it’s returned). - JVM must allocate it on the heap β escape analysis fails, no scalar replacement.
π Why this matters?
Without Graal (no escape analysis) | With Graal (escape + scalar) |
---|---|
Heap allocation (slow, GC load) | No allocation, just registers |
More work for GC | Less memory, faster execution |
Slower | 2xβ10x faster in tight loops |
π― Summary
Concept | What it means | Benefit |
---|---|---|
Escape Analysis | Does object stay inside method? | If yes β avoid heap |
Scalar Replacement | Replace object with its fields (scalars) | No allocation, faster |