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?
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.
Method. getModifiers() method returns the Java language modifiers for the method represented by this Method object, as an integer.
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.
Reflection is slower Because it involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With