Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Foreach loops and ressources

I'm using a foreach loop to process a large set of items, unfortunately it's using alot of memory. (probably because It's doing a copy of the array). Apparently there is a way to save some memory with the following code: $items = &$array;

Isn't it better to use for loops instead?

And is there a way to destroy each item as soon as they have been processed in a foreach loop.

eg.

    $items = &$array;
    foreach($items as $item)
    {
     dosomethingwithmy($item);
     destroy($item);
    }

I'm just looking for the best way to process a lot of items without running out of ressources.

like image 993
Roch Avatar asked Dec 17 '22 04:12

Roch


2 Answers

Try a for loop:

$keys = array_keys($array);
for ($i=0, $n=count($keys); $i<$n; ++$i) {
    $item = &$array[$keys[$i]];
    dosomethingwithmy($item);
    destroy($item);
}
like image 183
Gumbo Avatar answered Jan 01 '23 20:01

Gumbo


Resource-wise, your code will be more efficient if you use a for loop, instead of a foreach loop. Each iteration of your foreach loop will copy the current element in memory, which will take time and memory. Using for and accessing the current item with an index is a bit better and faster.

like image 24
Nicolas Avatar answered Jan 01 '23 22:01

Nicolas