Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If reflection in Java slows down execution by orders, why do so many frameworks use it ?

As per my understanding, use of Java reflection API slows down code execution by orders. But then I see it being used in so many places in Java universe. To name a few :

  • Annotations
  • Spring framework (AOP)
  • Hibernate
  • MyBatis

Which implies that there's some fact about java reflection (aka optimization technique) that I have missed out on. Any pointers ?

like image 424
Amit Sharma Avatar asked May 30 '13 07:05

Amit Sharma


2 Answers

Main point: because they have no other choice.

Java is not a dynamic language, so the only way these frameworks can provide their services is by reflection.

Second, notice that most of the reflection work these framework do happens only once, during initialization, so the runtime performance is not affected.

About the performance of reflection

There is one distinction that I notice being mixed up all the time:

  1. reflective lookup of members;
  2. reflective member access (invocation/read/write).

Number 1 is slow (this is the "orders" you mention); number 2 is the one that has received significant speed improvements and is now only a couple of times slower than native access.

like image 179
Marko Topolnik Avatar answered Oct 02 '22 12:10

Marko Topolnik


As a general rule, performance issues should be addressed by profiling. Leaving aside major improvements in reflection performance, all of those frameworks emphasize one-time lookups at startup (or later, in cases of lazy initialization). In the sort of enterprise app that uses them, that's not really relevant. As long as invoke is optimized, most of the penalty will go away.

like image 21
Andrew Lazarus Avatar answered Oct 02 '22 12:10

Andrew Lazarus