View previous topic :: View next topic |
Author |
Message |
sudu
Joined: 23 May 2004 Posts: 7
|
switch case vs if else performance |
Posted: Thu Oct 14, 2004 8:05 pm |
|
|
hi there,
just wanna to ask the different of switch and if-else operation performance. whitch one is faster. |
|
|
Trampas
Joined: 04 Sep 2004 Posts: 89 Location: NC
|
|
Posted: Thu Oct 14, 2004 8:08 pm |
|
|
Well it depends....
Kind of like asking which is faster a drag car or Nascar. It really depends on the application.
I would suggest you compile your code both ways if timing is critical and check.
Trampas |
|
|
Mark
Joined: 07 Sep 2003 Posts: 2838 Location: Atlanta, GA
|
|
Posted: Thu Oct 14, 2004 9:34 pm |
|
|
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. |
|
|
rnielsen
Joined: 23 Sep 2003 Posts: 852 Location: Utah
|
|
Posted: Fri Oct 15, 2004 8:19 am |
|
|
If your 'if()' sequence is very long then I would go with the switch() route. You could have, say, 10 if()'s that you're checking on and you have to compare each one to reach the last one. The switch() would do one comparison and then jump to the correct place without all of that wasted time. The switch() statement does create a fair amount of code though so, if size is not important then I would go with the switch().
Ronald |
|
|
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 |
|
|
|