使用反射创建对象而不是调用类构造函数会导致任何显着的性能差异吗?
最佳答案
是的 - 绝对是。通过反射查找一个类数量级更昂贵。
引用 Java's documentation on reflection :
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.
这是我在我的机器上用 5 分钟完成的一个简单测试,运行 Sun JRE 6u10:
public class Main {
public static void main(String[] args) throws Exception
{
doRegular();
doReflection();
}
public static void doRegular() throws Exception
{
long start = System.currentTimeMillis();
for (int i=0; i<1000000; i++)
{
A a = new A();
a.doSomeThing();
}
System.out.println(System.currentTimeMillis() - start);
}
public static void doReflection() throws Exception
{
long start = System.currentTimeMillis();
for (int i=0; i<1000000; i++)
{
A a = (A) Class.forName("misc.A").newInstance();
a.doSomeThing();
}
System.out.println(System.currentTimeMillis() - start);
}
}
有了这些结果:
35 // no reflection
465 // using reflection
请记住,查找和实例化是一起完成的,在某些情况下可以重构查找,但这只是一个基本示例。
即使您只是实例化,您仍然会受到性能影响:
30 // no reflection
47 // reflection using one lookup, only instantiating
再说一遍,YMMV。
关于Java 反射性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/435553/