I have a loop with 2 counters: i and j. If they have the same value - iteration works much faster than if their values differ:
Benchmark Mode Cnt Score Error Units
FloatsArrayBenchmark.times thrpt 20 341805.800 ± 1623.320 ops/s
FloatsArrayBenchmark.times2 thrpt 20 198764.909 ± 1608.387 ops/s
Java bytecode is identical, which means it's related to some lower level optimizations. Can someone explain why this is happening? Here's the benchmark:
import org.openjdk.jmh.annotations.*;
public class FloatsArrayBenchmark {
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(new String[]{FloatsArrayBenchmark.class.getSimpleName()});
}
@Benchmark @Fork(value = 1, warmups = 0)
public void times(Data data) {
float[] result = new float[10000];;
for (int i = 0, j=0; i < 9_999; i++,j++)
result[j] = data.floats[i] * 10;
}
@Benchmark @Fork(value = 1, warmups = 0)
public void times2(Data data) {
float[] result = new float[10000];
for (int i = 0,j=1; i < 9_999; i++,j++)
result[j] = data.floats[i] * 10;
}
@State(Scope.Benchmark)
public static class Data {
private final float[] floats = new float[10000];
}
}
Environment:
- MacOS, tried Java8, Java11, Java14
- 2,4 GHz Quad-Core Intel Core i5