iam using a switch case statement in which i
have around 100 case statements to compare.
it means that you have 100 constant values to compare against one
variable. In such cases, if else statement itself are converted
to switch statements if possible. but it should be confirmed from the
compiler group. comp.lang.gcc/g++ are two options
Also, are all the conditions exclusive i.e. are you putting
break statement in all the 100 cases or there are some fall through
also.
in both the cases it will be good to organize the code in a better way
yourself.
for example the following code
switch(i){
case 1: /* some code */ break;
case 2: /* some code */ break;
case 3: /* some code */ breask;
case 4: /* some code */ breask;
.
.
.
.
case 100: /* some code */ breask;
}
can be broken into
following tree to have less comparisons.
if(i <10){
switch(i){
case 1:
case 2:
.
.
} [...]
}else if (i < 50){ [...]
}
}
[...]
You're assuming that the generated code for the simple 100-case switch
statement performs up to 100 comparisons. A switch statement,
particularly when the values are tightly bunched, is typically
implemented as a jump table; the value of the expression is checked to
see whether it's within the range, and then used as an index for
something like a "computed goto".
Breaking up the switch statement into a sequence of if/else statements
and subsidiary switch statements is very likely to make the generated
code bigger and slower, and is certain to make it more difficult to
read and maintain.
Premature optimization is the root of all evil. Write code that's
clear, straightforward, and correct. As you're writing it, keep
efficiency concerns in mind, but don't obsess about them; for example,
don't use a if/else chain when a switch will do the job, and don't use
a O(N**2) algorithm when an O(N) algorithm is available. And don't
worry about low-level micro-optimizations; optimizing compilers are
good at handling those for you.
If the resulting code is fast enough, you're done. If it isn't,
measure it, figure out where the bottlenecks are, and consider doing a
few ugly micro-optimizations *if necessary*.