Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Improve PHP 'for' loop [duplicate]

When using a typical for loop, PHPStorm suggests to change it for better performance. I don't really understand the suggestion. How should I change it?

PHPStorm suggestion

like image 576
simPod Avatar asked Feb 01 '16 08:02

simPod


3 Answers

for($i = 0; $i <= count($data); $i++){}

In this example for every iteration it has to count($data) again.

for($i = 0, $iMax = count($data); $i <= $iMax; $i++){}

In this example it only needs to count($data) once.

That's the difference.

like image 105
Daan Avatar answered Nov 20 '22 20:11

Daan


If you execute the count() inside your for loop, then it's executed every iteration, and calling the function is a performance overhead.

If instead you call count() before the for loop and assign the result to a variable, then compare against the variable in the for loop, you don't haver the function call overhead, so it's faster

like image 20
Mark Baker Avatar answered Nov 20 '22 21:11

Mark Baker


By having the loop in the manner you do, each iteration it needs to evaluate count($data). If you've got a lot of items in the list, it could take a while (relatively) to count those items, and it has to do it each time.

The hint it is diving you is to set a variable to the value of count($data) at the beginning and then use that variable as the loop limit, when it's only evaluated once.

This can be done in two ways:

$loopMax = count($data);
for ($i = 0; $i <= $loopMax; $i++) {
    // Your code here
}

Or

for ($i=0, $loopMax = count($data); $i <= $loopMax; $i++) {
    // your code here
}
like image 12
gabe3886 Avatar answered Nov 20 '22 21:11

gabe3886