Does the time taken by a switch statement (or jump table in compiled form) to "decide" where to jump rise by the number of case
es it contains?
views:
130answers:
3Not really, there's usually a hash table or some other O(1) lookup data structure in the compiled code (unless you only have a tiny amount of switches, then the compiler may decide to use jumps instead). In general a large amount of switches should outperform a large amount of if statements, although normally you wouldn't have enough cases for it to be noticeable anyways.
It depends on the compiler and (typically) the values you supply -- if the values are "dense" (i.e., all or almost all values in a range have cases in the switch statement) you'll typically get a jump table, which takes the same time for all values (in that range). If you have relatively sparse values, it may compile to code roughly equivalent to an if/then/else ladder, in which case adding more (sparse) case values can increase execution time.
Why are you interested in that? That's a very low-level micro-optimization, which is very unlikely to yield any noticeable performance improvement, unless you have a very wickedly tweaked algorithm with every last nanosecond already squeezed out of it.
If you have a specific case, where you have proven that a switch
indeed is an important bottleneck, don't ask us (what do we know about your compiler, memory, processor etc.?), but measure yourself, using the tools you are using, in the environment you code is supposed to run.
In every other case just go on coding and try to write the code so that it is a readable as possible, instead of doing premature optimization.