D
Denis Remezov
Dave said:Hello all,
Consider the case of an if with many else if clauses vs. a switch with many
cases.
In thinking about how such control constructs would likely be implemented,
it would seem that neither would be superior to the other in terms of
execution speed of the generated code.
Would others agree that this is true for "typical" implementations?
Thanks,
Dave
For some reason I always expected the compilers to optimise a long switch
statement by using binary search. Now, the interesting part is that
gcc 3.3.3 appears to do exactly that (O(log n)), unless the range of values
is compact, in which case it uses a table (O(const)).
The if statement, on the other hand, in my tests was implemented literally,
without any clever optimisation.
For long selection lists the difference can be measurable. Though it comforts
me to think of it as of a potential bonus, I'd pick a switch over if whenever
appropriate regardless of the performance.
Denis