Branching vs modulo === The question is: when cyclically iterating through a fixed range, is it better to use the modulo operator on the index variable, or use a conditional branch once the index exceeds the range limit? That is to say, which of the following is better? ~~~ lang c++ for(int i=a; i!=b; i=(i+1)%N) for(int i=a; i!=b; i=(++i==N)?0:i) ~~~ The first option looks much cleaner and is easier to read. In non performance-critical systems, or if your programming project is not at the end of its development stage, you should _always_ use modulo. Never [prematurely optimize](http://en.wikipedia.org/wiki/Premature_optimization#When_to_optimize). Even if you were to optimize your program, you should probably start with a profiler instead of fiddling with little things like the modulo operator in loops. That said, I am currently writing a solver for the [Travelling Salesman Problem](http://en.wikipedia.org/wiki/Travelling_salesman_problem) where it is nice to have more speed. So I decided to find out which one is faster. Branching is generally bad in loops, but with [branch prediction](http://en.wikipedia.org/wiki/Branch_prediction) it really only needs to evaluate the condition once every loop. On the other hand, the expensive modulo operator would be evaluated up to N times per loop. # Test setup To test the performance, I made two simple C++ programs: `test_modulo.cpp` ~~~ lang c++ #include int main() { int N = 19739; long long x=0; for(int i=0; i<99999; i++) { for(int j=3; j!=2; j=(j+1)%N) x+=j; } std::cout< int main() { int N = 19739; long long x=0; for(int i=0; i<99999; i++) { for(int j=3; j!=2; j=(++j==N)?0:j) x+=j; } std::cout<