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?
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.
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.
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.
This is only way you can ever claim with any authority that one way is or is not faster than another.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With