A small research project exploring Escape Analysis and Scalar Replacement in JVM HotSpot using JMH and perfasm.
The project demonstrates how the JIT compiler can:
- completely eliminate object allocations;
- optimize non-escaping objects into scalar values;
- disable optimizations when object identity or escaping semantics are required.
The research was inspired by Aleksey Shipilëv’s article:
@Benchmark
public int scalarReplacement() {
Point p = new Point(x, 10);
return p.y + p.x;
}The object does not escape and does not require identity semantics.
HotSpot eliminates the allocation completely using Escape Analysis and Scalar Replacement.
@Benchmark
public int allocationWithoutEscape() {
Point p = new Point(x, 10);
return System.identityHashCode(p);
}System.identityHashCode() requires real object identity, forcing HotSpot to materialize the object and preventing Scalar Replacement.
@Benchmark
public Point allocationWithEscape() {
return new Point(x, 10);
}The object escapes from the method, so the allocation cannot be eliminated.
| Benchmark | Result |
|---|---|
scalarReplacement |
~0.8 ns/op |
allocationWithEscape |
~3.9 ns/op |
allocationWithoutEscape |
~56 ns/op |
The results show:
- Scalar Replacement can completely eliminate allocations;
- ordinary allocations in HotSpot are very cheap due to TLABs;
- object identity operations are significantly more expensive.
mvn clean installRun benchmarks:
java -jar target/benchmarks.jar -prof perfasm- Java 21
- JMH
- perfasm
- JUnit 5
This project is intended for educational and research purposes to better understand JVM internals, JIT optimizations, Escape Analysis, and allocation elimination in HotSpot.