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);
}
?>
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);
}
?>
That's it!
Let me know what you think?
Cover Image credits
Top comments (4)
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 usearray_map
.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.
Note that this is not specific to php.
Oh...I did not really think in that direction, may be I should just update the post. Thanks for your contribution.