为什么迭代超过10,000次的foreach循环会耗尽内存?


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

我正在开发一个PHP脚本,循环/迭代超过10,000次:

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;
}

当我运行这段代码时,我的机器内存不足。我可以做些什么来清理这个循环中的内存?

您正在实例化为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)检查内存消耗

在循环结束时尝试unset($obk_car)

unset: foreach循环结束的对象

unset($obj_car);

如果您仍然需要更多的脚本内存,您可以在php.ini中增加这一行的限制:

memory_limit = 128M

  • 如果你是PHP>= 5.3.0,你可以通过调用gc_collect_cycles
  • 强制垃圾收集
  • 如果您正在使用PHP>= 5.2,那么这篇来自IBM的文章将是一篇有趣的阅读。