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); } }
Results:
Note that this test includes both lookup and instantiation, but even isolating instantiation results in a penalty:
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!