Java反射性能 [英] Java Reflection Performance

查看:151
本文介绍了Java反射性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Does creating an object using reflection rather than calling the class constructor result in any significant performance differences?

推荐答案

是的 - 绝对。通过反思查找课程,按幅度,更贵。

Yes - absolutely. Looking up a class via reflection is, by magnitude, more expensive.

引用 Java关于反思的文档

由于反射涉及动态解析的类型,因此无法执行某些Java虚拟机优化。因此,反射操作的性能低于非反射操作,并且应避免在性能敏感应用程序中频繁调用的代码段中。

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:

Here's a simple test I hacked up in 5 minutes on my machine, running 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

请记住查找和实例化是一起完成的,在某些情况下,查找可以重构,但这只是一个基本的例子。

Bear in mind the lookup and the instantiation are done together, and in some cases the lookup can be refactored away, but this is just a basic example.

即使您只是实例化,您仍然会受到性能影响:

Even if you just instantiate, you still get a performance hit:

30 // no reflection
47 // reflection using one lookup, only instantiating

再次,YMMV。

这篇关于Java反射性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆