O'Reilly logo

Efficient C++ Performance Programming Techniques by David Mayhew, Dov Bulka

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required