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?
The less than or equal operator ( <= ) returns true if the left operand is less than or equal to the right operand, and false otherwise.
To check if a number is not greater than 0 , check if the number is less than or equal to 0 , e.g. num <= 0 . If the condition returns true , the number is not greater than 0 .
The less than operator ( < ) returns true if the left operand is less than the right operand, and false otherwise.
The machine level architecture will have OP codes for both < and <= operations and both comparisons can be made in one cycle of the CPU. Meaning it makes no difference.
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);
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With