title: Speed of exceptions in Java
body: <p>Using exceptions for normal flow of code is bad - it's slow, it's bad code quality, and we've all had this drummed into our heads from day 1. At least I have! This makes sense as well, exceptions generate stack traces each time they're called, stack traces take a long time to generate and thus an exception being thrown and caught is much slower than an equivalent if statement.</p>
  
  <p>So I decided to make a quick example to demonstrate this.</p>
  
  <pre><code>public static void main(String[] args) throws Exception {
      Object[] objs = new Object[500000];
      for (int i = 0; i &lt; objs.length; i++) {
          if (Math.random() &lt; 0.5) {
              objs[i] = new Object();
          }
      }
      long cur = System.currentTimeMillis();
      for (Object o : objs) {
          try {
              System.out.print(o.getClass());
          }
          catch (Exception e) {
              System.out.print("null");
          }
      }
      System.err.println("Try / catch: "+(System.currentTimeMillis() - cur));
      cur = System.currentTimeMillis();
      for (Object o : objs) {
          if(o==null) {
              System.out.print("null");
          }
          else {
              System.out.print(o.getClass());
          }
      }
      System.err.println("If: "+(System.currentTimeMillis() - cur));
  }
  </code></pre>
  
  <p>However, on running the code I was shocked to see the following:</p>
  
  <pre><code>Try / catch: 11204
  If: 11953
  </code></pre>
  
  <p>I ran the code again, this time "if" was faster:</p>
  
  <pre><code>Try / catch: 12188
  If: 12187
  </code></pre>
  
  <p>...but only by a ms.</p>
  
  <p>This is all run on the server VM, I know the majority of the time will be taken up by the <code>print()</code> statements, and some runs show if as a bit faster than try / catch. But regardless, surely they shouldn't even be close? And how on earth could generating stack traces be faster than a single if statement?</p>
  
  <p>EDIT: To clarify, this question is a purely academic one - I know full well using exceptions for the normal flow of code is bad and would never do so!</p>