#Case vs Map — Perf & Memo Considerations

8 messages · Page 1 of 1 (latest)

silent tartan
#

While looking at the Go http.StatusText() function, I noticed it uses a long switch case instead of something like a map[int]string.

I’m curious about the trade-offs:

  • Performance (lookup speed)
  • Memory usage
  • Any other practical impacts of choosing one over the other

When should you prefer a switch case, and when is a map the better option?

hallow sonnet
#

I prefer map for things like validation. As far as I know, using maps can be faster because it is branchless while using switches can be slower because a branch misprediction can happen.

Incidentally, this is why Bjorn Hoehrmann's UTF-8 DFA algorithm is often faster than other algorithms because it is branchless.

https://bjoern.hoehrmann.de/utf-8/decoder/dfa/

silent tartan
#

Case vs Map — Perf & Memo Considerations

wheat ruin
#

Lookup tables are quite far off from go maps. Maps are generally far slower because of the complexity related to their lookups, unlike lookup tables like the example above

quick urchin
royal comet
#

The compiler is pretty smart sometimes, if maps were really that fast it would rewrite your switch statement into a map.

#

They aren't in >99% of cases so it does not.

#

When you use a switch statement you're telling to the compiler « go wild with optimizations, this is never gonna change ».
In fact at some point we might get code that rewrite static maps to switch statements because how much people love to use them.