Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ switch table performance

Does the time taken by a switch statement (or jump table in compiled form) to "decide" where to jump rise by the number of casees it contains?

like image 508
asap Avatar asked Dec 18 '22 00:12

asap


2 Answers

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.

like image 168
Jerry Coffin Avatar answered Dec 24 '22 02:12

Jerry Coffin


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.