Reputation: 10677
I know that reflection is bit slow as all checks/validations are performed at run time.
Suppose i am instantiating a class using reflection and calling method on it. So my question is will the invocation be always slow ( even if its 1% slower than normal case) or only for the first time ? Assume that this class is part of my web application which gets called multiple times.
Another angle to my confusion is that now most of the modern JVMs use JIT compilers. So will not the JVM try to optimize the subsequent invocations.
Upvotes: 0
Views: 212
Reputation: 169018
Yes, the invocation will always be slow. The JIT-compiler optimizes the Java bytecode and compiles it to native code; it does not memoize or otherwise cache the results of methods, and calling into the reflection API means calling methods. The compiled native code will still call into the runtime's reflection facility on every invocation, and that is what is slow.
It will always be much slower to invoke a method using reflection than invoking it directly. However, note that the method's body will execute at normal speed -- it is only the process of invoking the method that will be slow.
As always, profile your code. If the instantiation and method invocation via reflection turn out to be bottlenecks, then optimize accordingly. (For example, if the invoked method is querying a database then that action is most likely to be your bottleneck, and the overhead introduced by reflection is very unlikely to be a problem.)
Upvotes: 1
Reputation: 16392
Yes, it's much slower even on successive calls. It's slow because there has to be invocation setup and tear-down behavior that would otherwise be hard-coded by the compiler in the byte codes.
Upvotes: 1