Dave wrote:
> 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?
No. Any half-decent compiler will reduce a switch statement to a jump
table, which is O(1) to the number of cases (assuming the cases are
sequential). A series of if-else statements will be reduced only by an
exceedingly clever compiler, and if compiled in the usual way will be O(n)
to the number of cases. An if statement will produce code with size
proportional to the number of cases, whereas a switch statement may produce
a very large mostly-empty table if the cases are sparse (depending on your
compiler.)
In fact, a switch statement is conceptually much more like a jump table
than like a series of if-else statements. Consider Duff's Device, for example:
switch(count%

{
case 0: do{ *to = *from++;
case 7: *to = *from++;
case 6: *to = *from++;
case 5: *to = *from++;
case 4: *to = *from++;
case 3: *to = *from++;
case 2: *to = *from++;
case 1: *to = *from++;
}while(--n>0);
}
--
CalcRogue: TI-89 and TI-92+. <http://www.gis.net/~wssddc/jimmy_b/>.