What are the performance costs involved in Java reflection? E.g., looking up a method by name and then invoking it.

Jef Newsom

The lookup is quite expensive (greater than an order of magnitude increase), but the invocation is relatively cheap (factor of 2).

Here are some stats from the simple program below. Although not the most perfect benchmark, consider running this or creating a similar test to see how expensive it will be for you.

100000 regular method calls:2664 milliseconds.
100000 reflective method calls without lookup:4216 milliseconds.
100000 reflective method calls with lookup:45505 milliseconds.
1000000 regular method calls:27840 milliseconds.
1000000 reflective method calls without lookup:43863 milliseconds.
1000000 reflective method calls with lookup:470947 milliseconds.

Obviously, if the execution time of the method is relatively large, the invocation overhead becomes negligible, at which point consideration of the cost of complexity overhead of the reflective code versus the amount of flexibility/code reduction becomes the primary concern.

Consider writing a simple test to confirm the performance impact in your environment, such as:
Object object = new Object();
Class c = Object.class;

int loops = 100000;

long start = System.currentTimeMillis();
for( int i = 0; i < loops; i++ )
{
object.toString();
}
System.out.println( loops + " regular method calls:" + (System.currentTimeMillis() - start) + " milliseconds." );
java.lang.reflect.Method method = c.getMethod( "toString", null );

start = System.currentTimeMillis();
for( int i = 0; i < loops; i++ )
{
method.invoke( object, null );
}

System.out.println( loops + " reflective method calls without lookup:" + (System.currentTimeMillis() - start) + " milliseconds." );
start = System.currentTimeMillis();
for( int i = 0; i < loops; i++ )
{
method = c.getMethod( "toString", null );
method.invoke( object, null );
}
System.out.println( loops + " reflective method calls with lookup:" + (System.currentTimeMillis() - start) + " milliseconds." );

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact