Java 反射性能 [英] Java Reflection Performance

查看:21
本文介绍了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天全站免登陆