Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reflection performance drops when packaged as jar

I have a real head-scratcher here. I tried everything, searched everywhere. It comes from an application I inherited that test JARs.

(It consists of a GUI front and a command-line application that does the actual checking. The GUI runs the command-line app by launching a new JVM on itself [java -cp "itself.jar" com.different.mainClass]. It's a bad design, I know, but may be relevant.)

Anyway, this program contains some reflection calls nested inside two for-loops. The problem is that when the application is JARed up, the first reflection call takes exactly one second every iteration. But when it runs from classes, it takes a few milliseconds.

Practically, this means this command:

java -jar myjar.jar

takes hours.

This command:

java -cp "...[bunch of jars];myjar.jar" com.myclasses.main

takes minutes.

The JAR being tested is always a jar. The difference is only in the test application.

Any ideas or avenues to pursue are greatly appreciated. Thank you!

like image 954
Michael Steinberg Avatar asked Jan 29 '13 02:01

Michael Steinberg


People also ask

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 Java Reflection costly?

In Java, it's widely admitted that reflection - usage of the java. reflect API, comes at a high cost in terms of performance.

Why is reflection slow?

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


1 Answers

You could consider running your program under a profiler like the Eclipse TPTP or YourKit and more precisely identify where your time is being spent. That will very likely point you to an error in your code, or somewhat less likely to point to a bug in a library. Then, if you cannot figure it out still, post the relevant code here and we can help out.

like image 58
Steven Schlansker Avatar answered Oct 10 '22 05:10

Steven Schlansker