Skip to content

Instantly share code, notes, and snippets.

@nikkatsa
Created October 19, 2019 11:41
Show Gist options
  • Save nikkatsa/69a58c63c1b79b245d700f6465bce7f7 to your computer and use it in GitHub Desktop.
Save nikkatsa/69a58c63c1b79b245d700f6465bce7f7 to your computer and use it in GitHub Desktop.
package com.nikoskatsanos.benchmarks.loops;
import java.util.ArrayList;
import java.util.List;
import org.openjdk.jmh.annotations.Benchmark;
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.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
@State(Scope.Benchmark)
public class SingleElementLoopBenchmark {
private final Dispatcher dispatcher = new Dispatcher();
@Benchmark
public void directInvocation(final Blackhole blackhole) {
this.dispatcher.invoke(blackhole);
}
@Benchmark
public void singleElementLoopInvocation(final Blackhole blackhole) {
this.dispatcher.invokeInLoop(blackhole);
}
@State(Scope.Benchmark)
public static class Dispatcher {
private final Listener listener = new Listener();
private final List<Listener> singleListenerList = new ArrayList<Listener>(){{add(listener);}};
public void invoke(final Blackhole blackhole){
this.listener.performAction(blackhole);
}
public void invokeInLoop(final Blackhole blackhole) {
for (int i = 0; i < this.singleListenerList.size(); i++) {
this.singleListenerList.get(i).performAction(blackhole);
}
}
}
public static class Listener {
void performAction(final Blackhole blackhole) {
blackhole.consume(true);
}
}
public static void main(final String... args) throws RunnerException {
final Options options = new OptionsBuilder()
.include(SingleElementLoopBenchmark.class.getSimpleName())
.forks(1)
.warmupIterations(10)
.measurementIterations(10)
.jvmArgs("-XX:+TieredCompilation", "-XX:+PrintCompilation")
.build();
new Runner(options).run();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment