Yes, this post is about the most basic concept that using
if/ else should be avoided within a loop as much as possible. Optimizing code is always important and when it’s about performance then the basic efficiency rules should be followed at first. Practically there are many situations when a loop iterates over large data set e.g. 10m; there may be differently required computation in the same loop- but if possible the loop should maintain branch prediction; avoid unnecessary
Following simple rules lead to performance advantage certainly. Branch prediction is a simple concept to optimize a loop-
Branch prediction– the very basic reason of processing a sorted array is faster than an unsorted array. There are many good references already available about it, that’s why I’m not elaborating about the same. A good read- processing a sorted array is faster than an unsorted array
if/ else in loop leads to performance benefit. If possible, avoid that, consider loop-invariant code motion. But when
if/ else is unavoidable in the loop, alternatives may be applied- like splitting the same loop or using bitwise operator etc. There are different possible scenarios when dividing a loop in multiple blocks is beneficial than keeping
if and computing the logic in a single loop.
Have a look at this most simple code block to realize the difference and advantages I’m talking about-
$ php branchPredictionPerformance.php Sum: 25002156375776 Sum1: 24997848624224 Total: 50000005000000 Random set with if/ else block processed in 0.21123886108398 s Sum: 24997838753761Sum: 25002166246239 Split random sets processed in 0.17409586906433 s Sum: 37499997499999 Sum1: 12500007500001 Total: 50000005000000 Sorted set with if/ else block processed in 0.21965599060059 s Sum: 12500002500000Sum: 37500002500000 Split sorted sets processed in 0.17140793800354 s
So the conclusion is
- The random set is taking longer time due to branch prediction failing.
- The random set processing is responded 21% faster when it has separated if/ else block in processing.
- Processing a sorted set is faster.
- The sorted set processing is responded 28% faster when it has separated if/ else block in processing.
Simple but useful, right?