Prefer Simple Calculations to Small Branches

As previously discussed, branching can be expensive in performance terms. Frequently, branching cannot be avoided, but sometimes branching is used in place of calculation. This can be a critical performance mistake. Take, for example, the following code sequence:

const int X_MAX = 16;
...
++x;
if (x >= X_MAX) {
    x = 0;
    }

It is really just a bit mask operation and can just as easily be done with the following code sequence:

const int X_MASK = 15;
...
x = (x + 1) & X_MASK;

In the first case there is a load, an increment, a store, a conditional test, and another store. Even on a machine with a short pipeline, the conditional test will cost at least three cycles, and thus the effective cost of the conditional ...

Get Efficient C++ Performance Programming Techniques now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.