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:
pis only used insidecompute().- It does not escape → so JVM doesn’t need to allocate
Pointon 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
Pointobject is created. It just usesxandy— this is scalar replacement.
đźš« What if object does escape?
public Point compute() {
Point p = new Point(5, 10);
return p; // Escapes the method
}
- Now
pescapes (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 |