sixlegs.com / blog / java / cglib-fastclass.html

Root Beer Logo Root Beer

Chris Nokleberg's Fizzy Weblog

September 2003
Su M Tu W Th F Sa
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 23 24 25 26 27
28 29 30
Previous  |  Next  |  More...
#  Optimizing reflection

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.01JDK 1.3.1.89
Time(ms)OverheadTime(ms)Overhead
Reflection7695.69683855.5
FastMethod4122.583221.66
FastClass+index3462.013331.75
Direct1150.001210.00

[Powered By FreeMarker]  [Valid Atom 1.0]  [Weblog Commenting by HaloScan.com]