title: HashMap vs Switch statement performance
body: <p>A HashMap essentially has O(1) performance while a switch state can have either O(1) or O(log(n)) depending on if the compiler uses a tableswitch or lookup switch.</p>
  
  <p>Understandably, if a switch statement is written as such,</p>
  
  <pre><code>switch (int) {
      case 1:
      case 2:
      case 3:
      case 4:
      default:
  }
  </code></pre>
  
  <p>then it would use a tableswitch and clearly have a performance advantage over a standard HashMap. But what if the switch statement is sparse? These would be two examples that I would be comparing:</p>
  
  <pre><code>HashMap&lt;Integer, String&gt; example = new HashMap&lt;Integer, String&gt;() {{
          put(1, "a");
          put(10, "b");
          put(100, "c");
          put(1000, "d");
  }};
  </code></pre>
  
  <p>.</p>
  
  <pre><code>switch (int) {
      case 1:
          return "a";
      case 10:
          return "b";
      case 100:
          return "c";
      case 1000:
          return "d";
      default:
          return null;
  }
  </code></pre>
  
  <p>What would provide more throughput, a lookupswitch or HashMap?
  Does the overhead of the HashMap give the lookupswitch an advantage early but eventually tapers off as the number of cases/entries increase?</p>
  
  <p><strong>Edit:</strong> I tried some benchmarks using JMH, here are my results and code used. <a href="https://gist.github.com/mooman219/bebbdc047889c7cfe612">https://gist.github.com/mooman219/bebbdc047889c7cfe612</a>
  As you guys mentioned, the lookupswitch statement outperformed the HashTable. I'm still wondering why though.</p>