Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does rearranging a conditional evaluation speed up a loop?

Bit of a weird one: I was told a while ago by a friend that rearranging this example for loop from :

for(int i = 0; i < constant; ++i) {
    // code...
}

to:

for(int i = 0; constant > i; ++i) {
    // code...
}

would slightly increase performance in C++. I don't see how comparing a constant value to a variable is faster than vice-versa, and some rudimentary tests I ran didn't show any difference in speed between the two implementations. The same was also true of testing this Python while loop:

while i < constant:
    # code...
    i += 1

vs:

while constant > i:
    # code...
    i += 1

Am I wrong? Are my simple tests not enough to determine the speed variation? Is this true of other languages? Or is this just a new best practice?

like image 305
WhatIsHeDoing Avatar asked Apr 09 '09 13:04

WhatIsHeDoing


3 Answers

It's more in the line of C++ folklore, hand micro-optimizations that worked once on a particular version of a particular compiler and get passed down ever after as some kind of lore distinguishing the possessor from the common herd. It's rubbish. Profiling is truth.

like image 113
chaos Avatar answered Oct 21 '22 16:10

chaos


Probably not, but if it did, the compiler would probably make the optimization for you automatically anyways. So do it whatever way makes your code most readable.

like image 36
Eric Petroelje Avatar answered Oct 21 '22 17:10

Eric Petroelje


My suspicion is your friend is 100% wrong. But I wouldn't trust my opinion anymore than I would trust your friend. In fact, if there is a performance problem there is only one person you should trust.

The Profiler

This is only way you can ever claim with any authority that one way is or is not faster than another.

like image 28
JaredPar Avatar answered Oct 21 '22 16:10

JaredPar