Reputation: 395
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?
Upvotes: 8
Views: 4064
Reputation: 4813
Measure it. Only then you can be absolutely sure which is faster.
You may think a lot about all the parts that play a role here (compiler, optimisation, processor, etc.). But in the end it is faster if it takes less time. It's as simple as that.
Upvotes: 2
Reputation: 20027
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);
.
Upvotes: 5
Reputation: 685
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.
Upvotes: 9