• Uncategorised
  • 0

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 inside compute().
  • 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 uses x and y β€” 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 GCLess memory, faster execution
Slower2x–10x faster in tight loops

🎯 Summary

ConceptWhat it meansBenefit
Escape AnalysisDoes object stay inside method?If yes β†’ avoid heap
Scalar ReplacementReplace object with its fields (scalars)No allocation, faster

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *