多个SELECT查询上的PDO / mysqli内存泄漏

时间:2018-09-15 20:14:24

标签: php mysql mysqli pdo memory-leaks

使用PDO或mysqli执行许多(20,000)个简单的SELECT操作时,内存泄漏。

// test2.php
$i = 0;
while (true) {

    $pdo->query("SELECT 1 as m");
    file_put_contents(__FILE__ . '.log', 'Memory: ' . memory_get_usage_in_mb() . PHP_EOL, FILE_APPEND);
    // In test2.php.log
    // ([line]: [message]):
    // 1:     Memory: 0.39
    // 5000:  Memory: 0.44
    // 10000: Memory: 0.51
    // 20000: Memory: 0.63

    if ($i === 20000) {
        break;
    }
    $i++;
}

请在https://gist.github.com/NewEXE/ca4f5ddbeb7ff863b8c775c238698c57上查看完整的测试代码

在每次查询后,我还尝试了PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false调用$pdo::closeCursor,并在mysqli情况下使用了此代码:

$result = $mysqli->query("SELECT 1 as m", MYSQLI_USE_RESULT); // and MYSQLI_STORE_RESULT too...

// with and without this lines:
$result->free_result();
$result = null;
unset($result);
  • 服务器:nginx / 1.13.6
  • PHP:7.2.7-1 + ubuntu16.04.1 + deb.sury.org + 1
  • MySQL:5.7.21-0ubuntu0.16.04.1
  • pdo_mysql:客户端API版本-mysqlnd 5.0.12-dev-20150407
  • mysqli:客户端API库版本-mysqlnd 5.0.12-dev-20150407

对不起,我的英语,谢谢您!

2 个答案:

答案 0 :(得分:0)

之后

$pdo = new \PDO($dsn, $dbParams['username'], $dbParams['password']);

添加此

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

测试两个文件

答案 1 :(得分:0)

I disabled xDebug and the problem is solved!

Tnanks to this answer: https://stackoverflow.com/a/43359644/8927920