I've read that modern C++ compilers turn large switch
blocks into binary trees for faster lookup at runtime, does this go for all modern C++ compilers? I'm mainly using Intel C++ compiler and G++.
The most efficient way, if your case
values are close to each other, is a jump table and this is what usually all compilers will aim for. If the values are sparse, then the compilers will usually go for the "binary-if-tree".
Best solution: Don't think about it. Just assume that a switch
is reasonably fast. Everything else smells like premature optimization. If you really encounter that a switch
is the bottleneck of your program, then you can only know what is generated by looking at the generated object code.
The compiler might even generate something totally different like a conditional move if you only assign a variable in each of the cases. So you can never know without looking at the generated assembly.
If you have a lot of sparse values, then using a hashtable might be faster than a switch
, since it is O(1)
in comparison to O(log n)
of the "binary-if-tree".