Re:Push ifs up and fors down
by kazinator on Thursday November 16, 2023 @01:59PM
(#38293793)
> The GOOD version is good, because it avoids repeatedly re-evaluating condition, removes a branch from the hot loop, and potentially unlocks vectorization.
Compilers can do that: notice that condition is not affected within the loop and hoist it outside.
Speaking of which, if the condition is affected by the loop, then the transformation is not correct. E.g. maybe the walruses appear in the list in a specific order, and an earlier walrus can determine a condition affecting the treatment of a later walrus.
Don't go into your code randomly swapping for and ifs.
Compilers can do that: notice that condition is not affected within the loop and hoist it outside.
Speaking of which, if the condition is affected by the loop, then the transformation is not correct. E.g. maybe the walruses appear in the list in a specific order, and an earlier walrus can determine a condition affecting the treatment of a later walrus.
Don't go into your code randomly swapping for and ifs.