Ttelmah Guest
|
|
Posted: Fri Oct 15, 2004 10:04 am |
|
|
Mark wrote: | I recall I believe it was RJ doing some tests and found that coding switch statements a certain way caused the compiler to create a jump table which was faster. If's and switch's are pretty comparable but I think the switch is more readable. |
It toggles depending on the size of the table, and the presence of a 'default'. If you have _no_ 'default' statement, and code:
Code: |
tval=getc();
switch (tval) {
case 0:
putc('0');
break;
case 1:
putc('1');
break;
case 2:
putc('2');
break;
case 3:
putc('3');
break;
case 4:
putc('4');
break;
case 5:
putc('5');
break;
}
|
A jump table will be generated. However if you code only three cases, it uses normal tests instead.
If you add a 'default', then normal tests are used.
Speed wise, the 'test' version, is the same as a series of 'if' statements. It ges slower the further down the tree the final branch is placed. The jump table, has more initial overhead, but the time involved is constant, for any entry.
So if the number of choices is large, the jump table version will be significantly faster for all except the first few choices. This is why CCS keep 'with' the test version for very small numbers of options.
Best Wishes |
|