I was microbenchmarking some kind of code (please be beautiful) and came across this puzzle: when reading a field using reflection, calling the getter method is faster than reading the field.
Simple testing class:
private static final class Foo { public Foo(double val) { this.val = val; } public double getVal() { return val; } public final double val;
We have two reflections:
Method m = Foo.class.getDeclaredMethod("getVal", null); Field f = Foo.class.getDeclaredField("val");
Now I call two reflections in the loop, invoke in the method and get in the field. The first start is performed to warm up the virtual machine, the second start is performed using 10M iterations. Calling a method sequentially is 30% faster, but why? Note that getDeclaredMethod and getDeclaredField are not called in a loop. They are called once and are executed on one object in a loop.
I also tried some minor variations: made the field non-confidential, transitional, non-public, etc. All of these combinations resulted in statistically similar performance.
Edit: This is on WinXP, Intel Core2 Duo, Sun JavaSE build 1.6.0_16-b01, running under jUnit4 and Eclipse.
source share