Search code examples
c++optimizationmicro-optimizationpremature-optimization

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?


Solution

  • 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.