有时候我们需要从MySQL中查询大量的数据, 如果直接放入到数组中, 再去遍历的很可能会产生内存饱满的情况, 这时, 我们可以利用php的生成器, 以减少内存的占用, 顺利的处理数据

    利用生成器的写法, 300多条的数据,内存占用 699048 byte

    1. <?php
    2. /**
    3. * Created by PhpStorm.
    4. * User: raye
    5. * Date: 18/1/12
    6. * Time: 17:08
    7. */
    8. class MysqlOperation{
    9. private static $instance;
    10. private function __construct()
    11. {
    12. $db_name = 'bi';
    13. $host = '192.168.1.100';
    14. $port = '3306';
    15. $c = [
    16. 'user' => 'root',
    17. 'pwd' => 123456,
    18. 'options' =>[]
    19. ];
    20. self::$instance = new \PDO("mysql:dbname=$db_name;host=$host;port=$port", $c['user'], $c['pwd'], (array)$c['options']);
    21. }
    22. public static function getInstance(){
    23. if (!self::$instance instanceof PDO) {
    24. new self();
    25. }
    26. return self::$instance;
    27. }
    28. }
    29. $func = function () {
    30. $mysql = MysqlOperation::getInstance();
    31. $statement = $mysql->prepare('SELECT uuid FROM `user`');
    32. $statement->execute();
    33. while ($row = $statement->fetch(PDO::FETCH_COLUMN)){
    34. yield $row;
    35. }
    36. };
    37. foreach ($func() as $item) {
    38. // var_dump($item);
    39. }
    40. var_dump(xdebug_peak_memory_usage());

    使用通常的写法, 内存占用762248 byte

    1. <?php
    2. $func = function () {
    3. $mysql = MysqlOperation::getInstance();
    4. $statement = $mysql->prepare('SELECT uuid FROM `user`');
    5. $statement->execute();
    6. $uuids = $statement->fetchAll(PDO::FETCH_COLUMN);
    7. return $uuids;
    8. };
    9. foreach ($func() as $item) {
    10. // var_dump($item);
    11. }
    12. var_dump(xdebug_peak_memory_usage());