在对查询结果集进行循环迭代时发生内存泄漏


Memory leak on loop iterating over query result set

我需要你的帮助超过内存限制在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()) {

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

您可能需要取消设置$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在循环中被重新分配,并且旧数据没有被一些垃圾收集和/或在内存中徘徊时,可能会发生"泄漏"

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

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