Strawberry
Strawberry

Reputation: 67868

In loops, does this matter?

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?

Upvotes: 2

Views: 129

Answers (5)

Aryabhatta
Aryabhatta

Reputation:

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?

Upvotes: 1

Dennis C
Dennis C

Reputation: 24747

It depends how will your optimizer do with your loop.

Upvotes: 0

Saem
Saem

Reputation: 3413

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?

Upvotes: 0

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

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

Upvotes: 2

Tyler Carter
Tyler Carter

Reputation: 61557

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.

Upvotes: 2

Related Questions