Java Reflection Performance

Question

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

Answer

Yes - absolutely.

Looking up a class via reflection is, by magnitude, more expensive.

Quoting Java's documentation on reflection:

Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.

Here's a simple test I hacked up in 5 minutes on my machine, running Sun JRE 6u10:

public class Main {

public static void main(String[] args) throws Exception{
    doRegular();
    doReflection();
}

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("misc.A").newInstance();
        a.doSomeThing();
    }
    System.out.println(System.currentTimeMillis() - start);
}

}

With these results:

35 // no reflection
465 // using reflection

Bear in mind the lookup and the instantiation are done together, and in some cases the lookup can be refactored away, but this is just a basic example.

Even if you just instantiate, you still get a performance hit:

30 // no reflection
47 // reflection using one lookup, only instantiating

Again, YMMV.

results matching ""

    No results matching ""