On Fri, 29 Jul 2005 06:45:40 -0700, swaroophr wrote:
Which of switch statement and if-else statement takes less time to
execute?
That depends on what code your compiler decides to generate for each one
and the environment (e.g. processor model) you are running the code on.
Different compilers can generate different code, the same compiler can
generate different code when given different options. The code the
compilergenerates for these will of course depend on the exact tests being
performed in each case, it can also depend on the code around each
statement. Of course for equivalent if-else and switch statements a
compiler could reasonably generate the same output code.
So there is no general answer to your question. For a particualr
combinatoin of code, compiler, compiler options and execution environment
the only reasonable way of geting an answer is to measure both and compare
them. Even that may not be conclusive, the results can depend enormously
on your input data. E.g. in an if-else chain that is translated fairly
directly by the compiler, if a lot of the time the first test matches it
will be fast, if a lot of the time the last test matches or no tests match
it is likely to be slower.
The best approach is usually to express what you want in the clearest way.
It is very often the case that is clearer to read is also easier for the
compiler to optimise.
Lawrence