Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reflection run-time performance

This is an academical exercise (disclaimer).

I'm building an application that will profit from being as fast as possible as it will compete with others.

I know that declaring a class using reflection (example below) will suffer a huge penalty as opposed to a standard declaration.

Class mDefinition = Class.forName("MySpecialClassString");
Constructor mConstructor = mDefinition.getConstructor(new Class[]{MySpecialClass.class});
myClass = (MySpecialClass) mConstructor.newInstance(this);

However, after declaring myClass if I use it in a standard fashion myClass.myMethod() will I also suffer from performance hogs or will it be the same as if I had declared the class in a standard fashion?

like image 447
Frankie Avatar asked Aug 19 '11 18:08

Frankie


People also ask

Is Java reflection good for performance?

Reflection is 104% slower than direct access (so about twice as slow). It also takes longer to warm up.

Why is Java reflection so slow?

Reflection is slow for a few obvious reasons: 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. Everything being invoked/created has to be discovered (i.e. classes looked up by name, methods looked at for matches etc)

Is reflection slow?

Reflection is slower Because it involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed.

What are the drawbacks of Java reflection?

Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability.


1 Answers

There will be a performance penalty when you first instantiate the object. Once the class is loaded, its the same as if it had been instantiated normally, and there will be no further performance penalty.

Going further, if you call methods using reflection, there will be a performance penalty for about fifteen times (default in Java), after which the reflected call will be rewritten by the JVM to be the exact same as a statically compiled call. Therefore, even repeatedly reflected method calls will not cause a performance decrease, once that bytecode has been recompiled by the JVM.

See these two link for more information on that:

  • Any way to further optimize Java reflective method invocation?
  • http://inferretuation.blogspot.com/2008/11/in-jit-we-trust.html
like image 83
Reverend Gonzo Avatar answered Sep 21 '22 13:09

Reverend Gonzo