Common Case First

  • by David Spuler, Ph.D.

Common Case First

When testing for a number of different conditions, it is best to test the most common case first. If it is true, the other tests are not executed. When using multiple if-else-if statements, place the common case first. For example, consider the binary search function:

    if (key > a[i]) {
        // ...
    }
    else if (key < a[i]) {
        // ...
    }
    else { // equality
        // ...
    }

Equality is least likely of all the three conditions, and hence it goes last. Greater-than and less-than are more common, so they go first.

The idea of common case first also appears in Boolean expressions using && or ||. The short-circuiting of these operators makes them very efficient when the common case is first. For ||, the most likely condition should be placed first (i.e. most likely to be true). For &&, the most unlikely condition should be placed first (i.e. most likely to be false).