Skip to content

Instantly share code, notes, and snippets.

@ddimtirov
Created November 2, 2013 07:01
Show Gist options
  • Save ddimtirov/7276373 to your computer and use it in GitHub Desktop.
Save ddimtirov/7276373 to your computer and use it in GitHub Desktop.
Flawed benchmark for reflection performance of Java. Don't do this. Circa 2005.
import java.util.Date;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
public class Benchmark {
public static int method(int parameter) {
return parameter%3 > 2 ? System.identityHashCode(new Date()) : -1;
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
long startInvocation = System.nanoTime();
for (int i = 0; i < 1000; i++) {
method((int) System.currentTimeMillis()%3);
}
long invocation = System.nanoTime() - startInvocation;
System.out.println("direct invocation (ns) = " + invocation);
long startReflection = System.nanoTime();
for (int i = 0; i < 1000; i++) {
Method rmethod = Foo.class.getMethod("method", int.class);
rmethod.invoke(null, (int) System.currentTimeMillis()%3);
}
long reflection = System.nanoTime() - startReflection;
System.out.println("reflection (ns) = " + reflection);
long startMI = System.nanoTime();
for (int i = 0; i < 1000; i++) {
MethodInvoker mi = new MethodInvoker(Foo.class.getMethod("method", int.class));
mi.invoke(null, (int) System.currentTimeMillis()%3);
}
long mi = System.nanoTime() - startMI;
System.out.println("MI (ns) = " + reflection);
System.out.println("slower = " + (float)invocation/reflection);
}
}
import java.lang.reflect.Method;
public class MethodInvoker {
final Method method;
public MethodInvoker(Method method) {
this.method = method;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment