Is it because we should load class (by string
for example), create instance, then search for appropriate method, pack parameters, and then just invoke method? So most time is spent on these operations instead of explicit method invocation on an object, right?
Adding setAccessible(true) call makes these reflection calls faster, but even then it takes 5.5 nanoseconds per call. Reflection is 104% slower than direct access (so about twice as slow).
Reflection is slow for a few obvious reasons: The compiler can do no optimization whatsoever as it can have no real idea about what you are doing. This probably goes for the JIT as well. Everything being invoked/created has to be discovered (i.e. classes looked up by name, methods looked at for matches etc)
Reflection will always be slower than direct calls, because you have to perform several steps to find and verify that what you're calling exists. It was always bad.... Of course sometimes you have no choice, its up to the programmer to know when those times are, and avoid it otherwise.
Reflection is not THAT slow. Invoking a method by reflection is about 3 times slower than the normal way. That is no problem if you do this just once or in non-critical situations. If you use it 10'000 times in a time-critical method, I would consider to change the implementation.
Every step you take needs to be validated every time you take it when you use reflection. For example, when you invoke a method, it needs to check whether the target is actually an instance of the declarer of the method, whether you've got the right number of arguments, whether each argument is of the right type, etc.
There's absolutely no possibility of inlining or other performance tricks.
If you're finding types or methods by name, that's at best going to involve a simple map lookup - which will be performed every time you execute it, rather than once at JIT time.
Basically there's a lot more to do. However, reflection has become a lot faster than it used to be... if you're finding it much too slow, you may well be overusing it.
As an addendum to Jon Skeet's answer above (I need more reputation in order to be able to comment.):
Reflection is dependent on CPU resources being available; if you have problem with your application being slow, reflection won't solve anything, just make it slower.
Like Java itself, reflection isn't slow any more - it is more of an old rumor ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With