Which would be the best/fastest way for evaluating the loop condition,orCode:while (i < x)? Assuming that the loop is incrementing i for each iteration, to avoid elitist remarksCode:while (i != x)
Which would be the best/fastest way for evaluating the loop condition,orCode:while (i < x)? Assuming that the loop is incrementing i for each iteration, to avoid elitist remarksCode:while (i != x)
Well assuming you know that i will at some point be exactly x, then there is no difference. But consider any possibility that might result in i never equaling x. Such as this:
Code:float i = 0.0; while (i != 1.0) { printf("%.2f\n", i); i += .1; }
Last edited by SlyMaelstrom; 03-04-2006 at 09:28 PM. Reason: Cause I had a for loop last time
Sent from my iPadŽ
Yes, the value of i will be the same as x's at some point, they are both integers and i is incrementing by one at a time.
I'm not an assembly expert, but I know on at least one architecture (ARM) those will both take exactly the same amount of time; cmp and then beq or bge (or bne vs blt); half a dozen in one hand and 6 in the other.Originally Posted by OnionKnight
But even if some architectures have one compare go faster than the other, don't give it any thought. Micro-optimization is bad. Forget "fastest" and just concentrate on "best" - whatever makes sense, is easy to understand and maintain. Always go good coding style.
hello, internet!
Yes I usually leave stuff like that up to the compiler but I figured that != would be the same as ! and ==, two operations whereas < would be just one but it seems like they actually do the same amount of work.
I've come to the conclusion that I'll use != in loops where the value will become the other at some point and < otherwise.
just for fun:
the first one seems to execute *slightly* faster than the second on my system, but it's negligible. I'd say follow moi's advice.Code:int main(void) { unsigned i, start, stop, first, second, max = UINT_MAX; i = 0; start = clock(); while(i < max) i++; stop = clock(); first = stop - start; i = 0; start = clock(); while(i != max) i++; stop = clock(); second = stop - start; cout << "(i < max): " << first << endl; cout << "(i != max): " << second << endl; }
Code:#include <cmath> #include <complex> bool euler_flip(bool value) { return std::pow ( std::complex<float>(std::exp(1.0)), std::complex<float>(0, 1) * std::complex<float>(std::atan(1.0) *(1 << (value + 2))) ).real() < 0; }