TIL of a PHP performance fix for for-loops
POSTED ON:
TAGS: php performance loops
This small detail is a performance issue.
<?php
$array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
for ($i = 0; $i < count($array); $i++;) {
}
Notice something?
It's running the count()
function every single loop.
For something this small, it's not a issue.
But if you're looping through a large array, it becomes a problem.
A simple fix is:
<?php
$array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
for ($i = 0, $count = count($array); $i < $count; $i++) {
}
In this version, you run the count()
function, and pass it over to the $count
variable. One call!
via Amir Etemad - Some Tips For PHP developers
Related TILs
Tagged: php