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?
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.
Not 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With