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);
Written by Daniel Pepin
Related protips
1 Response
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#