LoginSignup
29
33

More than 5 years have passed since last update.

PDOでfetchAll()は避けた方がいいのかもしれない

Last updated at Posted at 2016-07-02

たいていの場合、$stmt->fetchAll() でレコードセットを取得するコードを書いていたのですが、いかのようなコードで、ジェネレータを使ったらどうなるのかを実験してみました。

mst_address には郵政データ(123,909件)がそのまま入っています。

sample.php
<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

function get_pdo()
{
    $dsn = sprintf('mysql:dbname=%s;host=%s;charset=%s'
        , 'database'
        , 'localhost'
        , 'utf8'
    );
    $username = 'root';
    $password = 'password';
    $options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
    return new PDO($dsn, $username, $password, $options);
}

function fetch_array()
{
    $pdo = get_pdo();
    $statement = 'select * from mst_address';
    $stmt = $pdo->prepare($statement);
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function fetch_generator()
{
    $pdo = get_pdo();
    $statement = 'select * from mst_address';
    $stmt = $pdo->prepare($statement);
    $stmt->execute();
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        yield $row;
    }
}

//foreach (fetch_generator() as $row) {
//}

foreach (fetch_array() as $row) {
}

echo memory_get_peak_usage() . "\n";

結果

fetch_generator() を利用したとき

105340184

fetch_array() を利用したとき

496371488

結果は一目瞭然でした。

29
33
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
33