Q:Java Reflection Performance

D: Does creating an object using reflection rather than calling the class constructor result in any significant performance differences?

Test Case #7


File ID: #435568-0-cc


public static void doRegular() throws Exception {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i + +) {
            A a = new A();
            a.doSomething();
        }
        System.out.println(System.currentTimeMillis() - start);
    }
public static void doReflection() throws Exception {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i + +) {
            A a = (A) Class.forName("com.franciszabala.playground.A")
                  .newInstance();
            a.doSomething();
        }
        System.out.println(System.currentTimeMillis() - start);
    }

  1. K - let's not get carried away. Yes, the numbers are off due to optimizations. No, the test is no completely invalid. I added a call that removes any possibility of skewing the result, and the numbers are still stacked against reflection. In any case, remember that this is a very crude micro-benchmark which just shows that reflection always incurs a certain overhead
  2. On my machine the .newInstance() call with only one Class.forName() call scores 30 or so. Depending on VM version, the difference may be closer than you think with an appropriate caching strategy.
  3. Lawrey below pointed out that this test was completely invalid because the compiler was optimizing out the non-reflective solution (It can even prove that nothing is done and optimize out the for loop). Needs to be re-worked and should probably be removed from S.O. as bad / misleading information. Cache the created objects in an array in both cases to prevent the optimizer from optimizing it out. (It can not do this in the reflective situation because it can not prove that the constructor doesn't have side-effects)

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: