CCS C Software and Maintenance Offers
FAQFAQ   FAQForum Help   FAQOfficial CCS Support   SearchSearch  RegisterRegister 

ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

CCS does not monitor this forum on a regular basis.

Please do not post bug reports on this forum. Send them to CCS Technical Support

switch case vs if else performance

 
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion
View previous topic :: View next topic  
Author Message
Ttelmah
Guest







PostPosted: Fri Oct 15, 2004 10:04 am     Reply with quote

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
Display posts from previous:   
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group