我正在开发一个循环/迭代超过 10,000 次的 PHP 脚本:
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;
}
当我运行这段代码时,我的机器内存不足。我可以做些什么来清理这个 foreach 循环中的内存?
最佳答案
您正在将 CarAds 对象实例化为您的 $array_with_items 项目数。每一个分配内存。
在 save() 方法之后,您应该使用 unset() 函数释放对象:
// Saves to the database
$obj_car->save;
// Unset unneeded object
unset($obj_car);
您可以使用 memory_get_usage() 检查您的内存消耗(参见 http://php.net/manual/en/function.memory-get-usage.php )
关于php - 为什么迭代超过10,000次的foreach循环会耗尽内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8456493/