André
André

Reputation: 25584

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?

Upvotes: 6

Views: 3082

Answers (3)

Nasreddine
Nasreddine

Reputation: 37888

unset the object at the end of the foreach loop

unset($obj_car);

If you still need more memory for your script, you can increase the limit in your php.ini at this line :

memory_limit = 128M

Edit :

  • If you are on PHP >= 5.3.0 you can force garbage collectio by calling gc_collect_cycles
  • If you are using PHP >= 5.2, this article from IBM is an interesting read.

Upvotes: 2

spider
spider

Reputation: 1178

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)

Upvotes: 8

Alex
Alex

Reputation: 35158

Try unset($obk_car) at the end of the loop.

Upvotes: 5

Related Questions