// File Reflect4.java // The reflective call is 50 to 120 times slower than a virtual call. import java.lang.reflect.*; // Method class Reflect4 { public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { int count = Integer.parseInt(args[0]); Class ty = SomeClass.class; // Get SomeClass class Method m = ty.getMethod("m", new Class[] {}); // Get m() method SomeClass o = new SomeClass(); Object[] margs = new Object[] { }; Timer t1 = new Timer(); for (int i=count; i>0; i--) m.invoke(o, margs); System.out.println("Reflective call to o.m: " + t1.Check()); System.out.println(o.k); Timer t2 = new Timer(); for (int i=count; i>0; i--) o.m(); System.out.println("Virtual call to o.m: " + t2.Check()); System.out.println(o.k); SomeClassInterface oi = o; Timer t3 = new Timer(); for (int i=count; i>0; i--) oi.m(); System.out.println("Interface call to oi.m: " + t3.Check()); System.out.println(oi.getK()); } } class SomeClass implements SomeClassInterface { public int k = 1; public void m() { if (k > 0) k++; else { // Some dummy code with a recursive call to prevent inlining for (int j=k; j<=0; j++) { k++; m(); } } } public int getK() { return k; } } interface SomeClassInterface { public void m(); public int getK(); } // Crude timing utility ---------------------------------------- class Timer { private long start; public Timer() { start = System.currentTimeMillis(); } public double Check() { return (System.currentTimeMillis()-start)/1000.0; } }