Sub topic 11
Constant folding
This chapter assumes you know basic Java and annotations, can run Maven from the command line, and know that the JVM compiles hot code at runtime. It also assumes you have seen dead-code elimination and Blackhole, which the previous chapter covered.
What constant folding is
Constant folding is a compiler optimization. If the compiler can see that an expression always produces the same value, it computes that value once at compile time and replaces the expression with the result.
The JIT compiler does this too. If your benchmark calls Math.log(Math.PI), both the method and its input are known when the code is compiled. The JIT can compute the logarithm once and leave only a constant in the compiled code. The benchmark then measures almost nothing, and the score tells you nothing about Math.log.
Dead-code elimination removes work whose result is never used. Constant folding removes work whose result is already known. Returning the value or passing it to a Blackhole stops the first problem. It does not stop the second.
A benchmark that gets folded
Here is the last method from the earlier example, shown with its siblings:
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
}
}Compare returned with constantFolded. Both return a value, so neither suffers from dead-code elimination. The difference is the input. returned reads x, an instance field, so the JIT must load it on each call. constantFolded uses the compile-time constant Math.PI, which the JIT can fold.
Avoiding it
Read inputs from a non-final field of a @State object. The JIT cannot assume that a non-final field keeps its value, so it cannot precompute the result.
@State(Scope.Thread)
public class InputState {
public double x = Math.PI;
}Follow these rules:
- Do not pass literals or
static finalconstants into the code under test. - Do not declare state fields
final. The JIT may treat a final field as a constant. - Set the value in a field initializer or in a
@Setupmethod, as the@Statechapter showed. - Use
@Paramwhen you want several inputs. The value arrives through a field and is not known when the benchmark is compiled.
Recognizing a folded result
Folding rarely causes an error. It shows up as a score that looks too good:
- A time of a fraction of a nanosecond per operation, which is about the cost of an empty method.
- A score that stays the same when you change the input size.
- A score that matches an empty
@Benchmarkmethod.
If you suspect folding, add an empty benchmark as a baseline and compare. Then move the inputs into state fields and run again. A real computation should cost clearly more than the baseline and should respond to different inputs.
Exercise
A benchmark returns Math.sqrt(2.0) and reports 0.3 ns/op, the same as an empty benchmark. Why, and how do you fix it?
Show answer
The literal 2.0 and the pure method Math.sqrt let the JIT compute the result at compile time, so the loop only returns a constant. Put the value in a non-final field of a @State object, for example public double x = 2.0;, and return Math.sqrt(x). Check that the score now exceeds the empty-benchmark baseline.
Exercise
Why does returning the result from a benchmark method not protect you from constant folding?
Show answer
Returning the value only keeps the result alive, so the JIT cannot discard the work as dead code. If the value is already computable at compile time, the JIT can still replace the computation with a constant and return that.