Possible Duplicate:
Is it faster to count down than it is to count up?
I was reading a C++ book called C++ for You++. (I have the 1998 edition.)
In the chapter about Monte Carlo Methods there’s a snippet of code used to calculate definite integrals:
for(n = nPoints; n > 0; n--) { // A loop that goes down to
x = a + double(rand()) * ((b-a) / RAND_MAX); // 0 is slightly more efficient.
y = ...
... // if (y <= f(x)) increment count
...
}
My question is not about the code, rather about the comment:
A loop that goes down to 0 is slightly more efficient.
Is this true?????
Why would a loop going down to zero be more efficient than an ascending loop?
n, the loop counter, is not even used in the loop!
Again, this is not a pressing question. I am simply curious. I may have stumbled on a way to make my programs slightly more efficient!
I would expect that on a current processor, the effect would be negligible at best. However, it’s worth noting that processors have dedicated instructions for comparison to zero, which logically might be faster than comparison to a variable and might save a register. Thus, strictly speaking, it would be faster because the processor has an in-built special case for it.