Sub topic 11
Constant folding
This chapter assumes you can write a basic @Benchmark method, use @State classes, and know that the JIT compiler optimizes hot code at runtime. The previous chapter covered dead-code elimination, where the JIT removes work whose result is never used. Constant folding is a related problem. The work is kept, but the JIT does it once at compile time instead of on every call, so the benchmark measures almost nothing.
What constant folding is
Constant folding is a compiler optimization. When an expression depends only on values known at compile time, the compiler evaluates it once and replaces it with the result. For example, 2 * 60 * 60 becomes 7200. javac does this for simple expressions. The JIT compiler does it more aggressively, and it can fold calls to pure methods such as Math.log or Math.sqrt.
In ordinary programs this is a benefit. In a benchmark it is a measurement error, because the benchmark exists to time the computation. If the JIT knows every input, it can compute the answer while compiling and the benchmark method collapses to "return this number". You then measure the cost of returning a constant, which is usually a fraction of a nanosecond.
A benchmark that shows the problem
JMH's own samples use this pattern to compare folded and unfolded code. The class below measures the same logarithm four ways, plus a baseline.
package org.sample;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(2)
public class ConstantFoldBenchmark {
private double x = Math.PI; // plain field: JIT cannot assume its value
private final double wrongX = Math.PI; // final field initialized with a constant
@Benchmark
public double baseline() {
return Math.PI; // measures the cost of returning a value
}
@Benchmark
public double wrongLiteral() {
return Math.log(Math.PI); // constant argument, foldable
}
@Benchmark
public double wrongFinalField() {
return Math.log(wrongX); // final field, may also be folded
}
@Benchmark
public double right() {
return Math.log(x); // non-final state field, computed each call
}
}Build and run it with the setup from the earlier chapters:
mvn clean verify
java -jar target/benchmarks.jar ConstantFoldBenchmarkOn a typical JVM, baseline, wrongLiteral and wrongFinalField report nearly the same, very small score, because all three reduce to returning a precomputed value. right reports a clearly larger score, the real cost of Math.log. The exact numbers depend on your hardware and JVM, so compare the pattern rather than the values. If wrongLiteral is close to baseline, that is the sign of folding.
Why a state field avoids it
The JIT may only fold a value it can prove never changes. A literal such as Math.PI is a constant by definition. A static final field initialized with a constant is also treated as a constant. A non-final instance field is different. Any code could assign to it between calls, so the compiler must read it from memory each time and cannot replace Math.log(x) with a precomputed result.
final instance fields are a gray area. HotSpot does not trust them as constants in most cases, but this is an implementation detail and can change between JVM versions. Treat final on benchmark inputs as a risk. The simple rule is that benchmark inputs should be non-final fields of a @State object.
Here is the diagram of the decision the JIT makes:
The three habits that prevent folding
- Read inputs from non-final
@Statefields. Do not write literals orstatic finalconstants as arguments inside the benchmark method. - Do not mark benchmark inputs
final. Even if it works on your JVM today, you cannot rely on it. - Return or consume the result. Folding and dead-code elimination interact. If you fix one and forget the other, the JIT removes the work anyway. Return the value or pass it to a
Blackhole.
Combining all the fixes
The spine example FoldingBenchmark shows the four combinations side by side. This is the same class, with comments on what each method teaches.
package org.sample;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
@State(Scope.Thread)
public class FoldingBenchmark {
private double x = Math.PI;
@Benchmark
public void deadCode() {
Math.log(x); // result unused, the JIT may remove the call
}
@Benchmark
public double returned() {
return Math.log(x); // JMH consumes the returned value
}
@Benchmark
public void blackhole(Blackhole bh) {
bh.consume(Math.log(x)); // explicit consumption, useful for several results
}
@Benchmark
public double constantFolded() {
return Math.log(Math.PI); // constant input, the JIT may compute it at compile time
}
}deadCode fails because the result is discarded. constantFolded fails because the input is a constant. returned and blackhole are the two correct forms. Use returned when the method produces one value, and blackhole when it produces several.
Folding beyond a single call
Constant folding is not limited to math functions. These cases come up in real benchmarks.
- Constant collections. If a benchmark builds a
List.of(1, 2, 3)inside the method and sums it, the JIT may know the whole result. Build collections in@Setupand store them in non-final fields. - Constant array lengths. A
static final int[] DATA = new int[100]has a known length even if its contents are not constants. A loop overDATA.lengthcan be fully unrolled and optimized in ways that will not happen with data of an unknown size. Use@Paramfor sizes, as in the earlier chapter, so the size is not a compile-time constant. - Strings. String concatenation of literals is folded by
javacitself."a" + "b"is already"ab"in the class file, so benchmarking it measures nothing. - Loop invariants. Even with a state field, a computation inside a manual loop that does not depend on the loop variable can be hoisted out and done once. Do not add your own loop around the code you want to time. Let JMH invoke the method repeatedly, as the
@Benchmarkmethod is the unit of measurement.
How to detect folding
You cannot see folding in the source, so look for symptoms in the results.
- The score is close to an empty-method or
return constantbaseline. - The score does not change when you change the input size or value.
- The score is far below what the operation could physically cost, for example under 1 ns for a
Math.logcall.
Adding a baseline benchmark like the one above gives you a reference. If a method scores within the error range of the baseline, assume the work was eliminated and revisit the code. To confirm, run with the -prof perfasm profiler on Linux, which prints the generated assembly, or use -XX:+PrintCompilation and -XX:+PrintAssembly flags with a disassembler. These need extra setup, so most people rely on the baseline comparison.
Exercise
A benchmark method is @Benchmark public double sqrt() { return Math.sqrt(2.0); }. It reports 0.3 ns per operation, close to an empty method. Why, and how would you change it so it measures Math.sqrt?
Show answer
The argument 2.0 is a compile-time constant, so the JIT folds Math.sqrt(2.0) into a precomputed value and the method just returns it. Move the input into a non-final field of a @State class, for example private double v = 2.0;, and return Math.sqrt(v). The field is non-final, so the JIT cannot assume its value, and returning the result prevents dead-code elimination.
Exercise
You add private final int size = 1000; to your state class and loop to size in the benchmark. A colleague says this is safe because it is an instance field, not a static one. What is the risk, and what is the better design?
Show answer
Whether the JIT trusts a final instance field as a constant depends on the JVM implementation and version, so the loop bound might be folded and the loop optimized in ways that real data would not allow. The better design is a non-final field annotated with @Param, such as @Param({"1000"}) public int size;, which also makes it easy to compare other sizes.