Java 反射性能

标签 java performance optimization reflection

使用反射创建对象而不是调用类构造函数会导致任何显着的性能差异吗?

最佳答案

是的 - 绝对是。通过反射查找一个类数量级更昂贵。

引用 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/

相关文章:

Java Ucanaccess 将数据插入表中忽略重复记录(主键)

performance - 如何将 Oracle 用户配置文件投入实际使用?

ios - 循环处理时间太长

c++ - 给另一个 vector 内存的 std::vector 所有权?

image - Pagespeed 调整大小的图像质量低

java - 找不到 spark 应用程序输出

java - 如何在 Java 中的两个包之间共享包私有(private)数据?

c++ - 有效的容器,保持顺序并快速从任何位置删除元素

java - 将数字四舍五入到一定数量的位数 Java

algorithm - 如何决定这个时间复杂度