Often fields of atomic types e.g. AtomicInteger are explicitly zeroed at initialization, which is redundant and slower than relying on default values:
@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(value = Mode.AverageTime)
public class AtomicBenchmark {
@Benchmark
public Object defaultValue() {
return new AtomicInteger();
}
@Benchmark
public Object explicitValue() {
return new AtomicInteger(0);
}
}
Semantically both new AtomicInteger() and new AtomicInteger(0) are the same, but explicitValue() is much slower:
Benchmark Mode Cnt Score Error Units
AtomicBenchmark.defaultValue avgt 30 4.778 ± 0.403 ns/op
AtomicBenchmark.explicitValue avgt 30 11.846 ± 0.273 ns/op
This is related to https://github.com/spring-projects/spring-framework/pull/25261
Comment From: wind57
very interesting. this seems to happen because there is an explicit volatile
write, via : AtomicInteger(0)
.
Comment From: stsypanov
@wind57 yes, I've mentioned a previous PR being about the same: https://github.com/spring-projects/spring-framework/pull/25261
Also see https://bugs.openjdk.java.net/browse/JDK-8145680