Skip to content

Instantly share code, notes, and snippets.

@mattwarren
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattwarren/75c969ce58e72883a9a0 to your computer and use it in GitHub Desktop.
Save mattwarren/75c969ce58e72883a9a0 to your computer and use it in GitHub Desktop.
JMH Benchmark of Reflection Method Call v. Regular Method Call (against the same function)
package org.sample;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Setup;
import java.util.concurrent.TimeUnit;
import java.lang.reflect.*;
@State(Scope.Benchmark)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class MyBenchmark {
// Command line to run it:
// cls && java -jar .\target\benchmarks.jar MyBenchmark -i 10 -wi 10 -f 5 -bm avgt
private Object object = new Object();
private Class c = Object.class;
private java.lang.reflect.Method method;
@Setup
public void Setup() throws NoSuchMethodException {
method = c.getMethod("toString", null);
}
@Benchmark
public void baseline() {
}
@Benchmark
public String regularMethodCall() {
return object.toString();
}
@Benchmark
public String reflectionMethodCall() throws IllegalAccessException, InvocationTargetException {
return (String)method.invoke(object, null);
}
@Benchmark
public Object reflectionMethodCallNoCasting() throws IllegalAccessException, InvocationTargetException {
return method.invoke(object, null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment