tags:

views:

101

answers:

5

A

while( x < 100 ) {
if( x == 1 ) { echo "Hello World!" } else { echo "Bottles" }
x++;
}

B

while( x < 100 ) {
if( x != 1 ) { echo "Bottles" } else { echo "Hello World!"}
x++;
}

Would it really make a difference when having such a big loop?

+2  A: 

It probably won't make a difference.

I'd go with the second one, as it is more often that x != 1 than it will be that x == 1

This probably translates into super-tiny-1-thousandths-of-a-millisecond performance increase, but micro-optimization isn't that important.

Chacha102
I'd actually go with the first one for readability. Using negative conditions can be confusing if you have a lot of them.
musicfreak
+2  A: 

You're unlikely to notice any difference, and there are almost certainly bigger bottlenecks to worry about.

Matthew Flaschen
+1  A: 

On typical CPUs, B would likely be faster as branch prediction will probably be messed up for A. Assuming the compiler does not optimize, of course.

btw, did you measure it and find one to be substantially better than the other?

Moron
Except this is php where CPU branch prediction is not a factor.
John Knoeller
This is just theoretical. You can never tell which will be faster unless we measure it and even then we still can't be sure. And, it is hard to predict what the branch predictor would do, anyway :-)
Moron
A: 

I'm assuming x is starting from 1. If that's not the case this wouldn't necessarily be possible.

echo "Hello, World!";
while(x < 99) { echo "bottles"; x++; }

Why bother with the conditional, you know you're going to have to do it?

Saem
Your code assert x is 1 at the begin. how about this?while(x < 1) { echo "bottles"; x++; }if(x++==1) echo "Hello, World!"; while(x < 100) { echo "bottles"; x++; }
Dennis Cheung
A: 

It depends how will your optimizer do with your loop.

Dennis Cheung