I know that there are many topics talking about Reflection performance.
Even the official Java docs say Reflection is slower, but I have this code:
public class ReflectionTest { public static void main(String[] args) throws Exception { Object object = new Object(); Class<Object> c = Object.class; int loops = 100000; long start = System.currentTimeMillis(); Object s; for (int i = 0; i < loops; i++) { s = object.toString(); System.out.println(s); } long regularCalls = System.currentTimeMillis() - start; java.lang.reflect.Method method = c.getMethod("toString"); start = System.currentTimeMillis(); for (int i = 0; i < loops; i++) { s = method.invoke(object); System.out.println(s); } long reflectiveCalls = System.currentTimeMillis() - start; start = System.currentTimeMillis(); for (int i = 0; i < loops; i++) { method = c.getMethod("toString"); s = method.invoke(object); System.out.println(s); } long reflectiveLookup = System.currentTimeMillis() - start; System.out.println(loops + " regular method calls:" + regularCalls + " milliseconds."); System.out.println(loops + " reflective method calls without lookup:" + reflectiveCalls+ " milliseconds."); System.out.println(loops + " reflective method calls with lookup:" + reflectiveLookup + " milliseconds."); }
}
What I don't think is a valid benchmark, but at least should show some difference. I completed it, expecting that normal reflection calls would be slightly slower than normal.
But it prints this:
100000 regular method calls:1129 milliseconds. 100000 reflective method calls without lookup:910 milliseconds. 100000 reflective method calls with lookup:994 milliseconds.
Just for the record, I first performed it without this sysouts group, and then realized that some JVM optimizations just made it work faster, so I added this data to see if the reflection was even faster.
Result without sysouts:
100000 regular method calls:68 milliseconds. 100000 reflective method calls without lookup:48 milliseconds. 100000 reflective method calls with lookup:168 milliseconds.
I saw over the Internet that the same test performed on old JVMs makes reflective searchless twice as slow as regular calls, and this speed drops on new updates. If someone can do this and tell me that I'm wrong, or at least show me if there is something different from the past that accelerates its implementation.
Following the instructions, I ran each loop, divided, and the result (without sysouts)
100000 regular method calls:70 milliseconds. 100000 reflective method calls without lookup:120 milliseconds. 100000 reflective method calls with lookup:129 milliseconds.