title: Switch seems slower than if
body: <p>I was curious as to the speed on <code>switch</code>, believing that it was "very" fast, but I have a test case that seems to show a single switch is about as fast as about 4 <code>if</code> tests, when I expected (no solid reason) it to be as fast as 1 test. Here's the two methods I wrote to compare <code>switch</code> with <code>if</code>:</p>
  
  <pre><code>public static int useSwitch(int i) {
      switch (i) {
          case 1: return 2;
          case 2: return 3;
          case 3: return 4;
          case 4: return 5;
          case 5: return 6;
          case 6: return 7;
          default: return 0;
      }
  }
  
  public static int useIf(int i) {
      if (i == 1) return 2;
      if (i == 2) return 3;
      if (i == 3) return 4;
      if (i == 4) return 5;
      if (i == 5) return 6;
      if (i == 6) return 7;
      return 0;
  }
  </code></pre>
  
  <p>Here's my testing code:</p>
  
  <pre><code>long x = 0;
  for (int i = 0; i &lt; 999999; i++)
      x += useIf(i % 7); // I use "x" so calls won't get optimized out
  </code></pre>
  
  <p>And another identical loop for <code>useSwitch()</code></p>
  
  <p>On my machine these loops take <em>about the same time</em> to complete, which was a surprise.<br>
  I arrived at the number of ifs as "4", because that's the average given the input range (I think).<br>
  If I reduce the number of logic options, the <code>if</code> version is noticeably faster.</p>
  
  <p><br/>
  My question is:</p>
  
  <p>Is it that <code>switch</code> actually <em>isn't</em> that fast, or is this an "unfair" test in some way?</p>