java - 使用反射设置和获取的性能

标签 java reflection

是否使用反射(java.lang.reflect.Field getset 函数)设置和获取对象属性,而不是调用setget 对象本身,会导致任何显着的性能差异吗?

最佳答案

是的,基准测试很容易在 15 分钟内完成。

生成的代码更好,即使你缓存了反射访问器,我也试过了。

这里是在 Java 7 64 位下:

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 );
   }
}

结果:

20
37381
1677

比率接近 1870,但未设置可访问标志。设置它会使比率下降到 83。

关于java - 使用反射设置和获取的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12996053/

相关文章:

java - 方法始终返回零

java - 导入联系人仅导入联系人列表中的第一个联系人号码

go - 递归结构反射错误 : panic: reflect: Field of non-struct type

python - 如何按名称设置 Python 对象的字段/成员

c# - 如何在.net 3.5 中实现动态特性

Scala注解继承

java - 调用等待 HashMap 更改的函数

java - 完成测试后,chrome 浏览器不会关闭

java - 有人将 Ant4Eclipse 与 Project Lombok 一起使用过吗?

java - 从动态元素类型获取 ParametrizedType 对象