众所周知,可以使用方法来获取方法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倍。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句