Cost of invoking a method through reflection

First of all, if that method takes a long time to execute, the overhead of invoking it is insignificant.

This example program shows some performance differences in milliseconds.
- normal: execute a method normally
- same: execute a method through reflection, but use the same method instance
- diff: execute a method through reflection, but do a method lookup inside the loop

It turns out that looking up the method is rather expensive but invocation is fairly cheap.

Main.java:

import java.lang.reflect.*;
 
public class Main {
   public static void main(String args[]) throws Exception {
      Main main = new Main();
 
      System.out.println("#tNormaltSametDiffn");
      for (int i=1; i<1048577; i*=2) { 
         long time1 = main.performNormalCalls(i);
         long time2 = main.performSameReflectiveCalls(i);
         long time3 = main.performDiffReflectiveCalls(i);
 
         System.out.println(i + "t" + time1 + "t" + time2 + "t" + time3);
      }
   }
 
   public long performNormalCalls(int n) throws Exception {
      long start = System.currentTimeMillis();
      for (int i=0; i<n; i++) {
         test();
      }
      long end = System.currentTimeMillis();
 
      return (end - start);
   }
 
   public long performSameReflectiveCalls(int n) throws Exception {
      long start = System.currentTimeMillis();
      Method m = Main.class.getMethod("test", null);
      for (int i=0; i<n; i++) {
         m.invoke(this, null);
      }
      long end = System.currentTimeMillis();
 
      return (end - start);
   }
 
   public long performDiffReflectiveCalls(int n) throws Exception {
      long start = System.currentTimeMillis();
      for (int i=0; i<n; i++) {
         Method m = Main.class.getMethod("test", null);
         m.invoke(this, null);
      }
      long end = System.currentTimeMillis();
 
      return (end - start);
   }
 
   public void test() { }
}

outputs:

#	Normal	Same	Diff
 
1	0	0	0
2	0	0	0
4	0	0	0
8	0	0	0
16	0	0	0
32	0	0	0
64	0	0	0
128	0	0	0
256	0	0	0
512	0	0	0
1024	0	0	50
2048	0	0	60
4096	0	0	160
8192	0	60	220
16384	0	50	550
32768	0	60	990
65536	0	50	2030
131072	0	170	4010
262144	0	330	7800
524288	0	710	15540
1048576	60	1430	31090