Friday, February 13, 2009

Increase Performance of Loop with Large Arrays

In PHP, this is how we usually loop through arrays:


<?php
for ($i=0; $i<count($big_array); $i++){
//
}
?>


Having this approach, program will try to count the $big_array every time it loops and it may cause some performance issues. To make it more efficient, we should code it this way:


<?php
for ($i=0, $n=count($big_array); $i<$n; $i++){
//
}
?>


It does the counting during initialization only.

4 comments:

Anonymous said...

even faster and less memory consuming should be:

reset($big_array);
while ( list($key, $value) = each($big_array) ) {
//
}

hire php web developer india said...

I really loved read this blog. It has lot of information’s to the public. Thanks for sharing this information in internet

neenle said...

nice information,
thank you.

Healthcare software development company said...

Nice post regarding array used in PHP.