views:

1189

answers:

7

I've always avoided Java reflection soley based on its reputation for slowness. I reached a point in the design of my current project where being able to use it would make my code much more readable and elegant, so I decided to give it a go.

I was simply astonished by the difference, I noticed at times almost 100x longer run times. Even in this simple example where it just instantiates an empty class, it's unbelievable.

class B {

}

public class Test {

    public static long timeDiff(long old) {
     return System.currentTimeMillis() - old;
    }

    public static void main(String args[]) throws Exception {

     long numTrials = (long) Math.pow(10, 7);

     long millis;

     millis = System.currentTimeMillis();

     for (int i=0; i<numTrials; i++) {
      new B();
     }
     System.out.println("Normal instaniation took: "
                 + timeDiff(millis) + "ms");

     millis = System.currentTimeMillis();

     Class<B> c = B.class;

     for (int i=0; i<numTrials; i++) {
      c.newInstance();
     }

     System.out.println("Reflecting instantiation took:" 
              + timeDiff(millis) + "ms");

    }
}

So really, my questions are

  • Why is it this slow? Is there something I'm doing wrong? (even the example above demonstrates the difference). I have a hard time believing that it can really be 100x slower than normal instantiation.

  • Is there something else that can be better used for treating code as Data (bear in mind I'm stuck with Java for now)

+19  A: 

Reflection is slow for a few obvious reasons:

  1. The compiler can do no optimization whatsoever as it can have no real idea about what you are doing. This probably goes for the JIT as well
  2. Everything being invoked/created has to be discovered (i.e. classes looked up by name, methods looked at for matches etc)
  3. Arguments need to be dressed up via boxing/unboxing, packing into arrays, Exceptions wrapped in InvocationTargetExceptions and re-thrown etc.
  4. All the processing that Jon Skeet mentions here.

Just because something is 100x slower does not mean it is too slow for you assuming that reflection is the "right way" for you to design your program. For example, I imagine that IDEs make heavy use of reflection and my IDE is mostly OK from a performance perspective.

After all, the overhead of reflection is likely to pale into insignificance when compared with, say, parsing XML or accessing a database!

Another point to remember is that micro-benchmarks are a notoriously flawed mechanism for determining how fast something is in practice. As well as Tim Bender's remarks, the JVM takes time to "warm up", the JIT can re-optimize code hotspots on-the-fly etc.

oxbow_lakes
It cannot be over emphasized that using reflection is only slow compared to using the equivalent non-reflection code. Reading or writing to the HD or parsing xml or using the network or accessing a database (which is accessing HD and Network) are all slower than reflection.
Stefan Rusek
+1  A: 

100x sounds about right. That's the usual rule of thumb for the performance difference between a compiled and an interpreted implementation of the same language. Since reflection is a lot of what a Java interpreter would need to do, that seems reasonable.

Greg Hewgill
+11  A: 

The JITted code for instantiating B is incredibly lightweight. Basically it needs to allocate enough memory (which is just incrementing a pointer unless a GC is required) and that's about it - there's no constructor code to call really; I don't know whether the JIT skips it or not but either way there's not a lot to do.

Compare that with everything that reflection has to do:

  • Check that there's a parameterless constructor
  • Check the accessibility of the parameterless constructor
  • Check that the caller has access to use reflection at all
  • Work out (at execution time) how much space needs to be allocated
  • Call into the constructor code (because it won't know beforehand that the constructor is empty)

... and probably other things I haven't even thought of.

Typically reflection isn't used in a performance-critical context; if you need dynamic behaviour like that, you could use something like BCEL instead.

Jon Skeet
If constructing `B` doesn't do anything, it can be removed altogether. zOMG, reflection is infinitely slower!
Tom Hawtin - tackline
+2  A: 

Maybe you'll find this article interesting.

Geo
+19  A: 

Your test is flawed, the JVM is optimizing away your first for loop. If you simply new-up an object and discard it, the JVM might decide not to run that code. You should keep possible JVM optimizations in mind when writing tests. See below:

I ran your test on my system and got this:

Normal instaniation took: 109ms Reflecting instantiation took:15719ms

Then I modified it to maintain the reference to each of the objects in an array and got this:

Normal instaniation took: 3875ms Reflecting instantiation took:17484ms

Finally, I reordered which test runs first, to eliminate the GC running as a cause:

Reflecting instantiation took:17641ms Normal instaniation took: 1844ms

Modified test:

public class Test {

    static class B {

    }

    public static long timeDiff(long old) {
     return System.currentTimeMillis() - old;
    }

    public static void main(String args[]) throws Exception {
     int numTrials = 10000000;
     long millis;
     B[] Bees = new B[numTrials];

     millis = System.currentTimeMillis();
     Class<B> c = B.class;
     for (int i = 0; i < numTrials; i++) {
      Bees[i] = c.newInstance();
     }
     System.out.println("Reflecting instantiation took:" + timeDiff(millis)
       + "ms");

     millis = System.currentTimeMillis();
     for (int i = 0; i < numTrials; i++) {
      Bees[i] = new B();
     }
     System.out.println("Normal instaniation took: " + timeDiff(millis)
       + "ms");
    }
}
Tim Bender
Do you have an idea, why normal instantiation time varies so heavily?
Vanya
Nope. I noticed the discrepancy and wondered the same thing, but chose not to investigate.BTW, I discovered this is a repeat of:http://stackoverflow.com/questions/435553/java-reflection-performance...and I support both the main answer and Marcus Downing's contribution as the second answer.
Tim Bender
I do hope the JVM doesn't do this optimization if the constructor of B has a side effect?
Bart van Heukelom
+3  A: 

It seems that if you make the constructor accessible, it will execute much faster. Now it's only about 10-20 times slower than the other version.

    Constructor<B> c = B.class.getDeclaredConstructor();
    c.setAccessible(true);
    for (int i = 0; i < numTrials; i++) {
        c.newInstance();
    }

Normal instaniation took: 47ms
Reflecting instantiation took:718ms

And if you use the Server VM, it is able to optimize it more, so that it's only 3-4 times slower. This is quite typical performance. The article that Geo linked is a good read.

Normal instaniation took: 47ms
Reflecting instantiation took:140ms

But if you enable scalar replacement with -XX:+DoEscapeAnalysis then the JVM is able to optimize the regular instantiation away (it will be 0-15ms) but the reflective instantiation stays the same.

Esko Luontola
+1  A: 
  • Reflection was very slow when first introduced, but has been sped up considerably in newer JREs
  • Still, it might not be a good idea to use reflection in an inner loop
  • Reflection-based code has low potential for JIT-based optimizations
  • Reflection is mostly used in connecting loosely-coupled components, i.e. in looking up concrete classes and methods, where only interfaces are known: dependeny-injection frameworks, instantiating JDBC implementation classes or XML parsers. These uses can often be done once at system startup, so the small inefficiency don't matter anyway!
mfx