Skip to content

Instantly share code, notes, and snippets.

@ejain
Last active August 29, 2015 14:27
Show Gist options
  • Save ejain/06d2d69a46f8da0906af to your computer and use it in GitHub Desktop.
Save ejain/06d2d69a46f8da0906af to your computer and use it in GitHub Desktop.
A JMH microbenchmark comparing the performance of different looping constructs.
package benchmark;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;
@State(Scope.Benchmark)
public class LoopBenchmark {
private final List<Integer> values = new ArrayList<>(Collections.nCopies(1_000_000, 42));
@Benchmark
public void testBasicForLoop(Blackhole b) {
for (int i = 0; i < values.size(); ++i) {
b.consume(values.get(i));
}
}
@Benchmark
public void testForLoopWithCachedSize(Blackhole b) {
for (int i = 0, n = values.size(); i < n; ++i) {
b.consume(values.get(i));
}
}
@Benchmark
public void testForLoopWithCachedFinalSize(Blackhole b) {
final int n = values.size();
for (int i = 0; i < n; ++i) {
b.consume(values.get(i));
}
}
@Benchmark
public void testForLoopReverse(Blackhole b) {
for (int i = values.size(); --i >= 0;) {
b.consume(values.get(i));
}
}
@Benchmark
public void testForEach(Blackhole b) {
for (Integer value : values) {
b.consume(value);
}
}
@Benchmark
public void testForEachLambda(Blackhole b) {
values.forEach((value) -> b.consume(value));
}
public static void main(String... args) throws Exception {
Options opts = new OptionsBuilder()
.include(LoopBenchmark.class.getSimpleName())
.mode(Mode.Throughput)
.warmupIterations(1)
.warmupTime(TimeValue.seconds(5))
.measurementIterations(1)
.measurementTime(TimeValue.seconds(5))
.jvmArgs("-server")
.forks(1)
.build();
new Runner(opts).run();
}
}
Benchmark Mode Cnt Score Error Units
LoopBenchmark.testBasicForLoop thrpt 233.342 ops/s
LoopBenchmark.testForEach thrpt 210.694 ops/s
LoopBenchmark.testForEachLambda thrpt 235.284 ops/s
LoopBenchmark.testForLoopReverse thrpt 272.118 ops/s
LoopBenchmark.testForLoopWithCachedFinalSize thrpt 247.296 ops/s
LoopBenchmark.testForLoopWithCachedSize thrpt 249.025 ops/s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment