反射获取的方法的执行时间是否更长



众所周知,可以使用Reflection获取方法并通过返回的Method实例调用它。

然而,我的问题是;一旦它被Reflection获取并且我一遍又一遍地调用Method该方法的性能会比调用方法的正常方式慢吗?

例如:

import java.lang.reflect.Method;
public class ReflectionTest {
    private static Method test;
    public ReflectionTest() throws Exception {
        test = this.getClass().getMethod("testMethod", null);
    }
    public void testMethod() {
        //execute code here
    }
    public static void main(String[] args) throws Exception {
        ReflectionTest rt = new ReflectionTest();
        for (int i = 0; i < 1000; i++) {
            rt.test.invoke(null, null);
        }
        for (int i = 0; i < 1000; i++) {
            rt.testMethod();
        }
    }
}

我之所以问这个问题,是因为我正在制作一个事件系统,在注册侦听器时,它会扫描注释。这些方法被放入一个映射中,然后在每次发生所需参数类型的事件时执行它们。我不知道这是否足以提高性能,例如游戏。

使用不带反射的方法大约快一个数量级。我测试了它,就像

public static void main(String[] args) throws Exception {
    ReflectionTest rt = new ReflectionTest();
    // Warm up
    for (int i = 0; i < 100; i++) {
        test.invoke(rt, null);
    }
    for (int i = 0; i < 100; i++) {
        rt.testMethod();
    }
    long start = System.nanoTime();
    for (int i = 0; i < 10000; i++) {
        test.invoke(rt, null);
    }
    long end = Math.abs((start - System.nanoTime()) / 1000);
    start = System.nanoTime();
    for (int i = 0; i < 10000; i++) {
        rt.testMethod();
    }
    long end2 = Math.abs((start - System.nanoTime()) / 1000);
    System.out.printf("%d %d%n", end, end2);
}

我还test移动到static字段,以便它可以编译和运行

private static Method test;
static {
    try {
        test = ReflectionTest.class.getMethod("testMethod");
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    }
}

我得到了相当一致的差异(或输出一致)

4526 606

这表明跨10000调用反射比直接调用慢 ~7 倍。

@Elliot Frisch的回答提供了确凿的1证据,证明使用Method.invoke()速度较慢。

无论如何,您都会期望这一点,因为反射版本涉及额外的工作; 例如

  • 创建和初始化包含 varag 的数组,
  • 检查数组的长度,以及
  • 将数组中的参数从 Object 强制转换为相应的参数类型。

在某些情况下,JIT 可能会对此进行优化......


1 - 好的 ...定论。 该基准测试是有问题的,因为它没有采取适当的措施来处理可能的 JVM 预热异常。

相关内容

最新更新