Skip to content

Lewickiy/ScalarReplacement

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Scalar Replacement Research

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:

JVM Anatomy Quark #18: Scalar Replacement

Benchmarks

Scalar Replacement

@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.

Allocation Without Escape Analysis Optimization

@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.

Allocation With Escape

@Benchmark
public Point allocationWithEscape() {
    return new Point(x, 10);
}

The object escapes from the method, so the allocation cannot be eliminated.

Benchmark Results

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.

Running

mvn clean install

Run benchmarks:

java -jar target/benchmarks.jar -prof perfasm

Technologies

  • Java 21
  • JMH
  • perfasm
  • JUnit 5

Notes

This project is intended for educational and research purposes to better understand JVM internals, JIT optimizations, Escape Analysis, and allocation elimination in HotSpot.

About

A small research project exploring Escape Analysis and Scalar Replacement in JVM HotSpot using JMH and perfasm. Demonstrates how the JIT compiler can eliminate object allocations entirely and in which cases these optimizations stop working.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages