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
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 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.