Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Yes - absolutely.</strong> Looking up a class via reflection is, <em>by magnitude</em>, more expensive.</p> <p>Quoting <a href="http://java.sun.com/docs/books/tutorial/reflect/index.html" rel="noreferrer">Java's documentation on reflection</a>:</p> <blockquote> <p>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. </p> </blockquote> <p>Here's a simple test I hacked up in 5 minutes on my machine, running Sun JRE 6u10:</p> <pre><code>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&lt;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&lt;1000000; i++) { A a = (A) Class.forName("misc.A").newInstance(); a.doSomeThing(); } System.out.println(System.currentTimeMillis() - start); } } </code></pre> <p>With these results:</p> <pre><code>35 // no reflection 465 // using reflection </code></pre> <p>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.</p> <p>Even if you just instantiate, you still get a performance hit:</p> <pre><code>30 // no reflection 47 // reflection using one lookup, only instantiating </code></pre> <p>Again, YMMV.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload