循环中的内存泄漏迭代查询结果集

时间:2014-08-16 23:50:04

标签: php pdo doctrine-orm

PHP需要超出内存限制的帮助。 这是我的代码片段,导致问题:

$stmt = $query->execute(); // $stmt is instance of Doctrine\DBAL\Driver\PDOStatement
$before = $stmt->fetch();
while ($after = $stmt->fetch()) {
    // there will be some logic for comparsion of row pairs $before and $after,
    // but once the memory issue is fixed
    $before = $after;
    // tried unset($after); with no effect
}

错误信息是:

Fatal error: Allowed memory size of 134217728 bytes exhausted
(tried to allocate 24 bytes) in script.php on line 84

在线错误点:

while ($after = $stmt->fetch()) {

为了澄清,这是我真正运行的代码的一部分。这不是为了问我的问题而创建的伪代码。我在循环中注释掉了所有逻辑,以确保它不是原因。

2 个答案:

答案 0 :(得分:1)

可能您需要取消设置$before

$stmt = $query->execute(); // $stmt is instance of Doctrine\DBAL\Driver\PDOStatement
$before = $stmt->fetch();
while ($after = $stmt->fetch()) {
    // there will be some logic for comparsion of row pairs $before and $after,
    // but once the memory issue is fixed
    unset($before);
    $before = $after;

}
"泄漏"可能会在循环中重新分配$before并且旧数据未被某些垃圾收集删除和/或仍在内存中悬空时发生。

答案 1 :(得分:0)

解决方案非常简单。 PDO将整个结果缓冲到内存: 我不得不设置PDO属性

$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);