In Java, it’s widely admitted that reflection - usage of the java.reflect API, comes at a high cost in terms of performance. Older Java versions had huge performance overhead, while it seems that newer versions bring it in the acceptable range. But what does “acceptable” really mean?

This is the question I asked when commenting on a performance review that advised to replace code based on reflection by standard code. As many of our decisions are not based on facts but on beliefs, I decided to perform some tests to get metrics in Java 8.

Testing Protocol

In order to get realistic metrics through an unchallenged protocol, I used the excellent JMH testing framework. JMH has several advantages, among others:

An existing Maven artifact is readily available

Methods to benchmark have only to be annotated with @Benchmark

It handles the warming up of the JVM

It also handles the writing the results on the console

Here’s a JMH snippet:

@Benchmark
public void executePerformanceTest() {
// Code goes here
}

JMH will take care of executing the above executePerformanceTest() and taking care of measuring the time taken.

To highlight the cost of reflection, let’s check the difference between the time needed to access attributes with reflection and to call simple getters without.

Conclusion

Whatever the way results are displayed, it will take about 10 times more to access a field with reflection than without… on my machine. My guess is that this can be extrapolated to be true on any machine.

There’s a corollary conclusion: whatever you think holds true at a given time, you should always do some fact-checking to ensure a solid foundation for your decisions.

If you want to run the tests yourself, the project is available online in Maven format.