title: map vs switch performance in go
body: <p>Consider this benchmark, where we compare map access vs switch </p>
  
  <pre><code>var code = []int32{0, 10, 100, 100, 0, 10, 0, 10, 100, 14, 1000, 100, 1000, 0, 0, 10, 100, 1000, 10, 0, 1000, 12}
  var mapCode = map[int32]int32{
      0:    1,
      10:   2,
      100:  3,
      1000: 4,
  }
  
  func BenchmarkMap(b *testing.B) {
      success := int32(0)
      fail := int32(0)
      for n := 0; n &lt; b.N; n++ {
          // for each value in code array, do a specific action
          for _, v := range code {
              c, ok := mapCode[v]
              if !ok {
                  fail++
              } else {
                  success += c
              }
          }
      }
  }
  
  func BenchmarkSwitch(b *testing.B) {
      success := int32(0)
      fail := int32(0)
      for n := 0; n &lt; b.N; n++ {
          // for each value in code array, do a specific action
          for _, v := range code {
              switch v {
              case 0:
                  success++
              case 10:
                  success += 2
              case 100:
                  success += 3
              case 1000:
                  success += 4
              default:
                  fail++
              }
          }
      }
  }
  </code></pre>
  
  <p>Here is the results: </p>
  
  <pre><code>BenchmarkMap-2           5000000           277 ns/op           0 B/op          0 allocs/op
  BenchmarkSwitch-2       30000000            48.2 ns/op         0 B/op          0 allocs/op
  </code></pre>
  
  <p>So using map seems to be way slower than switch. </p>
  
  <p>I'm currently trying to optimize a function using a code similar to <code>BenchmarkMap()</code>, where the map access 
  is the bottleneck, but I can't use switch as the map is dynamically generated when the program start (ie it
  may change according to input arguments)</p>
  
  <p>Is there a way to get similar performance as <code>switch x {}</code> with dynamically generated map ? </p>