|
|
|||||||||||||||||||||||||||||||||||||||||||||
I decided to stop complaining about the speed of reflection and actually do something to help. In CGLIB CVS there is a new set of classes designed to replace common uses of java.lang.reflect. The API is intentionally similar, so you can replace code like:
Class c = String.class; Method m = c.getMethod("indexOf", new Class[]{ String.class } ); Integer i = (Integer)m.invoke("Hello", new Object[]{ "ll" } );with:
FastClass c = FastClass.create(String.class); FastMethod m = c.getMethod("indexOf", new Class[]{ String.class } ); Integer i = (Integer)m.invoke("Hello", new Object[]{ "ll" } );
For even more speed there is a special invoke-by-index feature:
FastClass c = FastClass.create(String.class); int m = c.getIndex("indexOf", new Class[]{ String.class } ); Integer i = (Integer)fc.invoke(m, "Hello", new Object[]{ "ll" } );
Reflection speed has increased quite a bit with recent JVMs, but even on 1.4.2 this code is significantly faster.
Update: By request, here are some real numbers. Two million iterations each on my Gentoo workstation. The "Overhead" column is ((Time - Direct) / Direct).
| JDK 1.4.2.01 | JDK 1.3.1.89 | |||
|---|---|---|---|---|
| Time(ms) | Overhead | Time(ms) | Overhead | |
| Reflection | 769 | 5.69 | 6838 | 55.5 |
| FastMethod | 412 | 2.58 | 322 | 1.66 |
| FastClass+index | 346 | 2.01 | 333 | 1.75 |
| Direct | 115 | 0.00 | 121 | 0.00 |