Home > Java > javaTutorial > How Much Does Reflection Impact Java Performance?

How Much Does Reflection Impact Java Performance?

Patricia Arquette
Release: 2024-12-05 04:19:14
Original
425 people have browsed it

How Much Does Reflection Impact Java Performance?

Does Reflection Affect Java Performance?

Creating objects using reflection, rather than calling the class constructor directly, undoubtedly incurs significant performance penalties. Reflection operations require dynamic type resolution, hindering Java virtual machine optimizations.

Java's documentation on reflection acknowledges this performance difference: "Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed...reflective operations have slower performance than their non-reflective counterparts."

A simple test reveals the stark difference:

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);
    }
}
Copy after login

Results:

  • Without reflection: 35ms
  • With reflection: 465ms

Note that this test includes both lookup and instantiation, but even isolating instantiation results in a penalty:

  • Without reflection: 30ms
  • With reflection (one lookup, only instantiating): 47ms

Thus, while the performance hit may vary depending on the specific context, it remains significant when using reflection.

The above is the detailed content of How Much Does Reflection Impact Java Performance?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template