The JLS states, that for arrays, "The enhanced for statement is equivalent to a basic for statement of the form". However if I check the generated bytecode for JDK8, for both variants different bytecode is generated, and if I try to measure the performance, surprisingly, the enhanced one seems to be giving better results(on jdk8)... Can someone advise why it's that? I'd guess it's because of incorrect jmh testing, so if it's that, please suggest how to fix that. (I know that JMH states not to test using loops, but I don't think this applies here, as I'm actually trying to measure the loops here)
My JMH testing was rather simple (probably too simple), but I cannot explain the results. Testing JMH code is below, typical results are:
JdkBenchmarks.enhanced avgt 5 2556.281 ± 31.789 ns/op
JdkBenchmarks.indexed avgt 5 4032.164 ± 100.121 ns/op
meaning typically enhanced for loop is faster, and measurement for it is more accurate than for indexed loop, so we cannot address the difference to measurement uncertainty. Principally the same results are for array initialized with random integers, or bigger arrays.
public class JdkBenchmarks {
@Benchmark
@BenchmarkMode(AverageTime)
@OutputTimeUnit(NANOSECONDS)
public void indexed(Blackhole blackhole, TestState testState) {
int length = testState.values.length;
for(int i = 0; i < length; i++) {
blackhole.consume(testState.values[i]);
}
}
@Benchmark
@BenchmarkMode(AverageTime)
@OutputTimeUnit(NANOSECONDS)
public void enhanced(Blackhole blackhole, TestState testState) {
for (int value : testState.values) {
blackhole.consume(value);
}
}
@State(Scope.Benchmark)
public static class TestState {
public int[] values;
@Setup
public void setupArray() {
int count = 1000;
values = new int[count];
for(int i = 0; i < count; i++) {
values[i] = i;
}
}
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(JdkBenchmarks.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
}