Tuesday, July 12, 2011

Performance of method invocation by reflection

One day discovering code in project I am working on I found the following code:

try {
    module.getClass().getMethod(methodName, Serializable.class).invoke(module, message);
} catch (Exception e) {
    throw e;
}        





Theoretically I knew that reflection works slower than direct invocation. But how slower?
Due to this code was found in the very performance critical part of the system I decided first to perform some benchmarking. I wrote class that contains one method foo() that does nothing and implemented 3 scenarios of invocation and ran them 1 million times:

  1. direct invocation
  2. invocation using reflection when getMethod() was called once
  3. invocation using reflection when getMethod() was called on each loop iteration. 
And here are the results.
  1. direct invocation took 5 ms
  2. reflection took 38 ms
  3. getMethod() + reflection invocation too 435 ms
This means that reflection generally can be used even in systems that are required to perform fast if getMethod() is not done for each invocation separately. 

1 comment: