Java reflection performance

For one of the projects to provide a piece of generic functionality I had to write a small library based on annotations and reflection. The reflective invocatons include new instance creation via java.lang.Constructor.newInstance(…) and field value retrieval via java.lang.Field.get(Object). Since this library had also to be efficient in terms of performance, I wanted to know how much reflective invocations of the above are slower than corresponding direct invocations (instance creation via “new” operator and field access via a direct getter method invocation). Also I wanted to know which of Field and a getter Method is more performant. To make long story short, the test showed that the difference is not significant. Worth mentioning that in the test I assumed that the reflection objects (the Field, the Method and the Constructor) are retreived in the “class scanning” phase and saved for later use.

Here is the performance test code:

Which has produced the following output (actually, the last repetitive piece of it) on my Intel Core i5 laptop:

100000 laps of Field took               19 ms
100000 laps of Method took              24 ms
100000 laps of Direct took              5 ms
100000 laps of Constructor took         19 ms
100000 laps of New operator took        2 ms
——
100000 laps of Field took               1 ms
100000 laps of Method took              4 ms
100000 laps of Direct took              1 ms
100000 laps of Constructor took         5 ms
100000 laps of New operator took        1 ms
——
100000 laps of Field took               1 ms
100000 laps of Method took              3 ms
100000 laps of Direct took              1 ms
100000 laps of Constructor took         2 ms
100000 laps of New operator took        1 ms
——
3 laps of All took              94 ms

Conclusion

As you can see, accessing a field via java.reflection.Field is almost as quick as via direct getter invocaton after a number of executions (when JIT compiler probably gets in). At the same time reflective getter invocation can be significantly slower. Respectively, object instantiation via java.reflection.Constructor is roughly twice slower than via “new” method.