Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of Set and Get using Reflection

Does setting and getting an object attribute using reflection (java.lang.reflect.Field get and set functions) rather than calling the set and get of the object itself, result in any significant performance differences?

like image 968
MBZ Avatar asked Oct 21 '12 08:10

MBZ


People also ask

Which method is used to get methods using reflection?

The getConstructors() method is used to get the public constructors of the class to which an object belongs. The getMethods() method is used to get the public methods of the class to which an object belongs.

Which method gets modifiers using reflection?

Method. getModifiers() method returns the Java language modifiers for the method represented by this Method object, as an integer.

How do you create a class object using reflection?

We can use newInstance() method on the constructor object to instantiate a new instance of the class. Since we use reflection when we don't have the classes information at compile time, we can assign it to Object and then further use reflection to access it's fields and invoke it's methods.

Why is reflection typically considered slow?

Reflection is slower Because it involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed.


1 Answers

Yes, the benchmark is easy to write in 15 minutes.

Generated code is better, even if you cache the reflective accessors, I have tried it.

Here it is under Java 7 64 bits:

import java.lang.reflect.Field;

class Data {
   public double _value;
   public double getValue()               { return _value; }
   public void   setValue( double value ) { _value = value; }
}

public class Reflect {
   public static final int LOOP_COUNT = 100_000_000;
   public static void main( String[] args ) throws Throwable {
      Data d = new Data();
      long start = System.currentTimeMillis();
      for( int i = 0; i < LOOP_COUNT; ++i ) {
         d.setValue( i );
      }
      System.err.println( System.currentTimeMillis() - start );
      Field field = Data.class.getDeclaredField( "_value" );
      start = System.currentTimeMillis();
      for( int i = 0; i < LOOP_COUNT; ++i ) {
         field.set( d, new Double( i ));
      }
      System.err.println( System.currentTimeMillis() - start );

      field.setAccessible( true ); // Optimization
      start = System.currentTimeMillis();
      for( int i = 0; i < LOOP_COUNT; ++i ) {
         field.set( d, new Double( i ));
      }
      System.err.println( System.currentTimeMillis() - start );
   }
}

Result:

20
37381
1677

Ratio is near 1870 w/o accessible flag set. Setting it makes ratio drop to 83.

like image 190
Aubin Avatar answered Oct 17 '22 08:10

Aubin