Does switch statement determines appropriate case statement in same execution time for either of possible input values?
Does it compare input value with case blocks and jumps to appropriate case when upon finding the value that it was looking for?
Consider example below. Does switch statement execute in same time for input = 1 or input = 256 or does it execute slower for latter value?
int output, input = 256;
switch( input )
{
case 1:
output = 1;
break;
case 2:
output = 2;
break;
case 4:
output = 3;
break;
case 8:
output = 4;
break;
case 16:
output = 5;
break;
case 32:
output = 6;
break;
case 64:
output = 7;
break;
case 128:
output = 8;
break;
case 256:
output = 9;
break;
default:
output = 0;
break;
}
Does
switchstatement execute in same time forinput = 1orinput = 256or does it execute slower for latter value?
The language does not specify.
Implementations commonly implement some switch statements with the use of jump tables, which makes the switch take approximately the same amount of time regardless of the control value. However, they may also use multiple branches, exactly as for an if / else if tree, which takes a longer time to process for some control values than for others. They may use other strategies as well.
Those that choose among multiple possibilities commonly do so on the basis of the case values that must be supported.