chapter2: switch O(n)
Author: rvansaCreated Mar 7, 2019Updated Feb 5, 2024
I actually got surprised that type switches are O(N).
"how else could it work?"
I would assume that since the list of hashes is known at compile time, the compiler could find a perfect hashing function and just do a few arithmetic ops to get the address on which to jump1. At least if the size of switch exceeds some threshold.
If finding perfect hash would be too time-consuming, it could at least sort the hashes and do a binary search.
I guess the answer is that this is one of the optimizations Go is still awaiting...
EDIT: 1 Actually it would need to get just an index and lookup the target address; compiler knows the list of target hashes but not all input hashes.
Source: teh-cmc/go-internals