If I lookup a method using Reflection and then cache that method, is it any slower than it would have been to call the method directly?
method.invoke(myInstance, new Object[]{} );
VS.
myInstance.myMethod();
If I lookup a method using Reflection and then cache that method, is it any slower than it would have been to call the method directly?
method.invoke(myInstance, new Object[]{} );
VS.
myInstance.myMethod();
I’d say yes.
I’ve never noticed any overhead myself, but logically it’s having to pass through at least one more function call (Method.invoke())before getting to the method itself, and the invoke() method will have to check the types of the Objects you’ve passed it before execution.
Don’t know how much more overhead this adds up to though. Anyone got any experience of this?
Yes, it can be considerably slower because Hotspot is not able to inline the method or perform any other little tricks on it - it’s like calling a pure virtual function in C++, indirectly, that can’t be inlined. It’s a lot faster than it used to be though.
Don’t use this in performance critical code.
Cas
From: Effective Java
[quote]As of release 1.3, reflective method invocation was 40 times slower than normal method invocation. In 1.4 refection was reworked and is now only about twice as slow as normal invocation.
[/quote]
(The above is actually a summary)
in 1.4 the invocation time is just a bit slower, in previous JDK it was horrible
Maybe you can get around this by having that class implement a Interface that is known at compile time?
Yup, Leknor guided me to this in another thread.