switch
is nice because it can filter out input that is outside the range of your case statements. So if you are checking each number between 1 and 40, as opposed to an
if/else
chain where each conditional has to be evaluated,
switch
will jump to the
default
case (vis it''s jump table algorithms) if the input is outside the range.
Sometimes a
switch
statement won''t compile into a jump table if the range of the case numbers is too large. For example:
switch(i){ case 11: { // Stuff } break; case 9: { // Stuff } break; case 4: case 4: { // Stuff } break; case 15: { // Stuff } break; case 9999: { // Stuff } break; default: break;}
The compiler isn''t going to generate a jump table for this because it needs at least a byte for every integer between 4 and 9999 in addition to the addresses to jump to for each case... now that''s just a lot of useless "code" if the compiler were to use a jump table (as jump table addresses are compiled into the code segment)
This would turn into a cmp/je chain as Jan suggested.
You have to consider a whole bunch of things when you think about whether or not to use a
switch
. In terms of memory, each case statement itself (including the default case if it executes some code) will need four CS bytes for a pointer, and each integer value in-between your high/low case values will need a CS byte as a table index. The switch statement also generates the code to check for out-of-range values, as well as find the index into the jump table, and finally jump to the stored address.
In terms of speed, switch has to perform additional instructions to work properly, as mentioned above. It has to use a few indirections (if
byte ptr [edx]
is considered an indirection in assembly) for the jump table.
You will be better off using an
if/else
chain if you only have a few cases. Once you get past 8, 9, or 10 cases, however, then it''s time to consider a switch statement.
You know what? You would be best off disassembling some code an taking a look yourself