Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a foreach loop which iterates more than 10,000 times run out of memory?

I'm developing a PHP script that loops/iterates more that 10,000 times:

foreach ($array_with_items as $item) {

    // Instantiate the object
    $obj_car = new CarAds($puk, 'ENG', '5');

    $obj_car->detail1 = "Info about detail1";
    $obj_car->detail2 = "Info about detail2";
    $obj_car->detail3 = "Info about detail3";
    $obj_car->detail4 = "Info about detail4";

    // Saves to the database
    $obk_car->save;
}

When I run this code my machine runs out of memory. What can I do to clean the memory in this foreach cycle?

like image 359
André Avatar asked Dec 10 '11 12:12

André


People also ask

Why for loop is faster than foreach?

This foreach loop is faster because the local variable that stores the value of the element in the array is faster to access than an element in the array. The forloop is faster than the foreach loop if the array must only be accessed once per iteration.

Is foreach loop faster than for loop Java?

Foreach performance is approximately 6 times slower than FOR / FOREACH performance. The FOR loop without length caching works 3 times slower on lists, comparing to arrays. The FOR loop with length caching works 2 times slower on lists, comparing to arrays.

Is foreach better than for loop Java?

forEach() can be implemented to be faster than for-each loop, because the iterable knows the best way to iterate its elements, as opposed to the standard iterator way. So the difference is loop internally or loop externally.

Is foreach faster than while?

There is no major "performance" difference, because the differences are located inside the logic. You use foreach for array iteration, without integers as keys. You use for for array iteration with integers as keys. etc.


1 Answers

You are instantiating as CarAds objects as your $array_with_items item count. Each one allocate memory.

After the save() method you should deallocate the object with the unset() function:

// Saves to the database
$obj_car->save;

// Unset unneeded object
unset($obj_car);

You can check your memory consumption with the memory_get_usage() (see http://php.net/manual/en/function.memory-get-usage.php)

like image 114
spider Avatar answered Oct 15 '22 21:10

spider