php: Optimise forloop with this tip
Chidiebere Chukwudi

Chidiebere Chukwudi @jovialcore

About: Software Developer. php| laravel | cakephp | vuejs/Nuxt | wordpress | Bootstrap | Tailwind

Location:
Nigeria
Joined:
Jan 10, 2018

php: Optimise forloop with this tip

Publish Date: Jul 28 '22
3 4

This is not a long lists of whats and what-not-to-do when using the forloop syntax in php. It's just a tip I got from official php doc. Also this tip is not specific to php

For the following example, take note of the count() method:

Sometimes, It's a common thing to many php developers to iterate through arrays like in the example below.

<?php
$vehicles = array(
    array('name' => 'toyota', 'salt' => 856412),
    array('name' => 'ford', 'salt' => 215863)
);

for($i = 0; $i < count($vehicles); ++$i) {
    $people[$i]['salt'] = mt_rand(000000, 999999);
}
?>
Enter fullscreen mode Exit fullscreen mode

According to official php doc, the above code can be slow because it has to count count($people); the array size for every iteration but most of the time, the size is usually constant hence, you can optimise by using an intermediate variable to hold/store the size instead of repeatedly calling count().. See example below:

<?php
$vehicles = array(
    array('name' => 'toyota', 'salt' => 856412),
    array('name' => 'ford', 'salt' => 215863)
);
$size = count($vehicles);
for($i = 0; $i < $size; ++$i) {
    $people[$i]['salt'] = mt_rand(000000, 999999);
}
?>
Enter fullscreen mode Exit fullscreen mode

That's it!

Let me know what you think?
Cover Image credits

Comments 4 total

  • Ben Sinclair
    Ben SinclairJul 28, 2022

    Unless it's a very big array, this won't make much difference. Still, I'd use foreach instead, because you don't need to keep track of the index then. Better yet, for something like this, I'd use array_map.

    • Vincent Milum Jr
      Vincent Milum JrJul 30, 2022

      The array size doesn't actually matter for count(). The size of the array is stored along with the array contents, so its not actually "counting" the number of objects each time, instead just pulling that value. PHP's documentation is a simplistic example, but in reality, it is only saving a couple CPU cycles at best. It is a very VERY minor "micro-optimization" when it comes to count(), but would be more impactful for a more computationally complex method call.

  • Julien Dephix
    Julien DephixJul 28, 2022

    Note that this is not specific to php.

    • Chidiebere Chukwudi
      Chidiebere ChukwudiJul 30, 2022

      Oh...I did not really think in that direction, may be I should just update the post. Thanks for your contribution.

Add comment