dxrkaa
Last Updated: February 25, 2016
·
1.867K
· donutdan4114
Drupal logo 1

PHP count() is very slow.

Don't be stuck making this mistake, which I've seen many times:

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

For the uninitiated, the $i < count($my_array) and $i++ are run every time the loop cycles. To alleviate this computationally intensive operation, simply set a variable:

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

*hint: the same idea applies to a while and do loop.

while($i < $count){ $i++; }

do{ $i++; }while($i < $count);
Say Thanks
Respond

2 Responses
Add your response

946
Photo by peter jakubowski uwm photo services   201

Any insight on how this method measures up?

foreach($myarrayitems as $item){ ... }
over 1 year ago ·
985
Drupal logo 1

This site http://m.metamorphosite.com/php-benchmarks-loops-arrays would suggest that foreach loops are actually very fast most of the time. However, I think they naturally take up more memory when you're using them. But using references can fix that:

foreach($myarray as &$ref){ ... }
over 1 year ago ·