[Java] [Java] Is reflection really heavy? Performance comparison

1 minute read

Purpose

I wanted to use reflection when creating the base class, but since I had the information that reflection is heavy, is it really heavy? I want to know how heavy it is, so I actually measure it.

Verification environment

  • Eclipse Oxygen.3a Release (4.7.3a)
  • Java8

Source code for verification

1. Normal instantiation

qiita.java


private static Oimo getInstance01() throws Exception {
return new Oimo();
}

2. Instance generation using reflection

qiita.java


private static Oimo getInstance02() throws Exception {
Class<?> clazz = Class.forName("kensho01.Oimo");
return (Oimo) clazz.newInstance();
}

Implementation procedure

  • Generate the instance 100,000 times using the verification source code and calculate the average time by measuring 3 times each. Round to the second decimal place.

Implementation result

1. Normal instantiation

  • 1st time: 4 ms
  • Second time: 3 ms
  • 3rd time: 3 ms
  • Average: 3.33 ms

2. Instance generation using reflection

  • 1st time: 63 ms
  • Second time: 69 ms
  • 3rd time: 65 ms
  • Average: 65.67 ms

Consideration

It can be seen that the normal instance generation takes 3.33 ms on average, while the instance generation using reflection takes 65.67 ms on average, which is about 20 times longer. From this, it is clear that the instance generation using reflection is heavy, and the use for the source code of the product should be avoided as much as possible, apart from the test code.

See you again (^_^)