Last active
August 29, 2015 14:11
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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