Reputation: 25584
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
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 :
gc_collect_cycles
Upvotes: 2
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