Search code examples
c++loopsoptimizationoperators

Is It More Efficient to Do a Less Than comparison OR a Less Than Or Equal To?


I'm wondering if it's more efficient to do a less than or equal to comparison in a loop or a less than comparison. Does the <= operator instruct the computer to make two comparisons (is it less than, is it equal to), or does it simplify it? Take the following example. I want a loop than increments to 1000. Should I set the ceiling to 1001 and tell it that while i is < (OR !=) 1001, i++;? Or should I tell it that while i <= 1000, i++;? Will the compiler (GCC) simplify it to the same basic instructions?


Solution

  • It depends on the architecture.

    The original von Neumann IAS architecture (1945) did have only >= comparison.

    Intel 8086 can use Loop label paradigm, which corresponds to do { } while (--cx > 0);
    In legacy architectures, LOOP was not only smaller, but faster. In modern architectures LOOP is considered complex operation, which is slower than dec ecx; jnz label; When optimizing for size (-Os) this can still have significance.

    Further considerations are that some (RISC) architectures do not have explicit flag registers. Then comparison can't be given free, as a side effect of loop decrement. Some RISC architectures have also a special 'zero' register, which means, that comparison (and every other mathematical operations) with zero is always available. RISCs with jump delay slots may even benefit from using post decrement: do { } while (a-- > 0);

    An optimizing compiler should be able to convert a simple loop regardless of the syntax to the most optimized version for the given architecture. A complex loop would have a dependency to the iterator, side effects, or both: for (i=0;i<5;i++) func(i);.