Java Reflection: Why is it so slow?

JavaPerformanceReflection

Java Problem Overview


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)

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

Your test may be flawed. Generally though the JVM may optimize the normal instantiation but could not make optimizations for the reflective use case.

For those wondering what the times were, I added a warmup phase and used an array to maintain the created objects (more similar to what a real program might do). I ran the test code on my OSX, jdk7 system and got this:

> Reflecting instantiation took:5180ms
> Normal instaniation took: 2001ms

Modified test:

public class Test {

	static class B {

	}

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

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

		int numTrials = 10000000;
		B[] bees = new B[numTrials];
		Class<B> c = B.class;
		for (int i = 0; i < numTrials; i++) {
			bees[i] = c.newInstance();
		}
		for (int i = 0; i < numTrials; i++) {
			bees[i] = new B();
		}

		long nanos;

		nanos = System.nanoTime();
		for (int i = 0; i < numTrials; i++) {
			bees[i] = c.newInstance();
		}
		System.out.println("Reflecting instantiation took:" + TimeUnit.NANOSECONDS.toMillis(timeDiff(nanos)) + "ms");

		nanos = System.nanoTime();
		for (int i = 0; i < numTrials; i++) {
			bees[i] = new B();
		}
		System.out.println("Normal instaniation took: " + TimeUnit.NANOSECONDS.toMillis(timeDiff(nanos)) + "ms");
	}
	
	
}

Solution 3 - Java

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.

Solution 4 - Java

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.

Solution 5 - Java

  • 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!

Solution 6 - Java

@Tim Bender 's code give these results on my machine(jdk_1.8_45, os_x 10.10, i7, 16G):

Reflecting instantiation took:1139ms
Normal instaniation took: 4969ms

so it seems on modern JVM, the reflection code will be optimized also well.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMikeView Question on Stackoverflow
Solution 1 - Javaoxbow_lakesView Answer on Stackoverflow
Solution 2 - JavaTim BenderView Answer on Stackoverflow
Solution 3 - JavaJon SkeetView Answer on Stackoverflow
Solution 4 - JavaEsko LuontolaView Answer on Stackoverflow
Solution 5 - JavamfxView Answer on Stackoverflow
Solution 6 - JavabobView Answer on Stackoverflow