且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java反射性能

更新时间:2023-08-24 12:10:46

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

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。