Java reflection Method invocations yield result faster than Fields?

Posted by omerkudat on Stack Overflow See other posts from Stack Overflow or by omerkudat
Published on 2011-01-04T11:38:33Z Indexed on 2011/01/04 11:53 UTC
Read the original article Hit count: 142

Filed under:
|
|

I was microbenchmarking some code (please be nice) and came across this puzzle: when reading a field using reflection, invoking the getter Method is faster than reading the Field.

Simple test class:

private static final class Foo {
    public Foo(double val) {
        this.val = val;
    }
    public double getVal() { return val; }
    public final double val; // only public for demo purposes
}

We have two reflections:

Method m = Foo.class.getDeclaredMethod("getVal", null);
Field  f = Foo.class.getDeclaredField("val");

Now I call the two reflections in a loop, invoke on the Method, and get on the Field. A first run is done to warm up the VM, a second run is done with 10M iterations. The Method invocation is consistently 30% faster, but why? Note that getDeclaredMethod and getDeclaredField are not called in the loop. They are called once and executed on the same object in the loop.

I also tried some minor variations: made the field non-final, transitive, 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.

© Stack Overflow or respective owner

Related posts about java

Related posts about Performance