I have the following cycle:
//condition will be set here to true or false
for (int i = 0; i < LARGE_NUMBER; i++) {
if (condition) {
//do foo
} else {
//do bar
}
}
Assumption: A cycle if faster without a condition than with a condition. (Is this true?)
Question: Will gcc factor out my if, if condition has been set outside the for cycle, and the cycle itself doesn’t touch condition?
If not, I should switch the if and the for, duplicate code, violate DRY, etc.
For those who don’t wish to read a lengthy post, this optimization is called (in LLVM) Loop Unswitch.
Why not ask a compiler ?
Is transformed into SSA form (via LLVM try out):
Not too readable perhaps, so let me point out what’s here:
entry: check ifargcis equal to 0, if it is, go tobb5(exit) else go tobb.nphbb.nph: compute the value ofcondition, if it’s true, go tobb3.uselse go tobb3bb3.usandbb3: loops for the true and false condition respectivelybb5: exitA compiler can pretty much transform your code how it wants, as long as the effect is similar to what you asked for. In this case, it has effectively rewritten the code as:
It’s a form of Loop Invariant Optimization, combined here with a first check to avoid computing the condition if the loop is not going to get executed.
For those of us who would think the first solution is clearer, we’re quite happy to have the compiler do the nitty gritty optimization for us!