title: Java Reflection: Why is it so slow?
body: <p>I've always avoided Java reflection soley based on its reputation for slowness. I reached a point in the design of my current project where being able to use it would make my code much more readable and elegant, so I decided to give it a go. </p>
  
  <p>I was simply astonished by the difference, I noticed at times almost 100x longer run times. Even in this simple example where it just instantiates an empty class, it's unbelievable.</p>
  
  <pre><code>class B {
  
  }
  
  public class Test {
  
      public static long timeDiff(long old) {
          return System.currentTimeMillis() - old;
      }
  
      public static void main(String args[]) throws Exception {
  
          long numTrials = (long) Math.pow(10, 7);
  
          long millis;
  
          millis = System.currentTimeMillis();
  
          for (int i=0; i&lt;numTrials; i++) {
              new B();
          }
          System.out.println("Normal instaniation took: "
                   + timeDiff(millis) + "ms");
  
          millis = System.currentTimeMillis();
  
          Class&lt;B&gt; c = B.class;
  
          for (int i=0; i&lt;numTrials; i++) {
              c.newInstance();
          }
  
          System.out.println("Reflecting instantiation took:" 
                + timeDiff(millis) + "ms");
  
      }
  }
  </code></pre>
  
  <p>So really, my questions are</p>
  
  <ul>
  <li><p>Why is it this slow? Is there something I'm doing wrong? (even the example above demonstrates the difference). I have a hard time believing that it can really be 100x slower than normal instantiation.</p></li>
  <li><p>Is there something else that can be better used for treating code as Data (bear in mind I'm stuck with Java for now)</p></li>
  </ul>