Monday, March 3, 2008

Regular method call vice call through reflection

A few weeks ago I had a pleasure to discuss some Java topics with three Java guys. Each of them has much more experience than I do. One of those topics was a performance of method call through reflection vice regular method call. Those three guys were confident that the difference in performance is not significant. And I argued that it is. Our discussion ended, but I was curious what is that difference.
So, here is the little test I wrote, sound like the famous song of Bobby McFerrin ;) :

import java.lang.reflect.Method;


public class ReflectionSpeedTest {

public static void main(String[] args) {
int times = 100000;
long simpleCallTime = simpleCall(times);
long reflectionCallTime = reflectionCall(times);

System.out.println("number of calls: " + times);
System.out.println("simple call time: " + simpleCallTime);
System.out.println("reflection call time: " + reflectionCallTime);
}


private static long simpleCall(int times) {
ReflectionSpeedTest worker = new ReflectionSpeedTest();

long time = System.currentTimeMillis();

for (int i = 0; i < times; i++) {
worker.doWork();
}

return System.currentTimeMillis() - time;
}


private static long reflectionCall(int times) {
try {
Class workerClass = Class.forName("ReflectionSpeedTest");
Object workerInstance = workerClass.newInstance();
Method method = workerClass.getMethod("doWork", null);

long time = System.currentTimeMillis();

for (int i = 0; i < times; i++) {
method.invoke(workerInstance, null);
}

return System.currentTimeMillis() - time;
} catch (Exception e) {
throw new RuntimeException(e);
}
}


public void doWork() {
int i = 5 * 6;
}
}

You can download this test from inworg.com if you want try it by yourself. Regularly the whole java poem is needed to call a single method through reflection (you need the class, the method and often also the instance). This test does not tests that case. Only method call is measured.
On my machine running openSUSE 10.3 the reflection call was more than 10 times slower. For sure, this difference may be not so significant for heavy methods, but for light ones it is.

No comments: