switch Statement Performance Consideration


Desktop-as-a-Service Designed for Any Cloud ? Nutanix Frame

Environment: General

Here is an example of a switch statement:

switch( parameter )
case 1: { ... } ; break;
case 2: { ... } ; break;
case 3: { ... } ; break;
default: { ... } ; break;

If one looks at the assembly code generated for this, one notices that there are two portions:

Portion 1:

contains a list of compares and jumps for each of the cases listed within the switch statement.

Portion 2:

Contains code that implements each of the cases.

The list in portion one is something like:

  • compare parameter with 1 , if equal jump to case 1 code start
  • compare parameter with 2 , if equal jump to case 2 code start
  • compare parameter with 3 , if equal jump to case 3 code start
  • and so on

    Note that, the list is in the order in which the cases have been listed.

    Looking at this, it is a better idea to have cases that have more chances of occurence to be put in the beginning than at the end so that, they don't have to go through unnecessary comparisons. This is mostly applicable where the switch statements are present in function bodies which are called often, for example, Window procedures, call back function etc. In such cases, cases which could happen often , like WM_PAINT, WM_MOUSEmessages, WM_KEYDOWN etc can be pushed up in the order.

    It certainly cannot be used when fall through is used for certain cases, but, in a general sense, it surely is a good programming practice.

  • Comments

    • Creating a Business Blog That Increases Sales

      Posted by nelpexela on 11/20/2012 11:45am

      I was more than happy to seek out this web-site.I desired to thanks for some time because of this amazing read!! I definitely enjoying every little little it and I've you bookmarked to have a look at new stuff you blog post. Am I Allowed To just say what a relief to uncover an individual who really knows what theyre speaking about online. NFL Jerseys NFL Jerseys

    • You must have javascript enabled in order to post comments.

    Leave a Comment
    • Your email address will not be published. All fields are required.

    Most Popular Programming Stories

    More for Developers

    RSS Feeds

    Thanks for your registration, follow us on our social networks to keep up-to-date