switch Statement Performance Consideration

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.

  • More by Author

    Must Read