Doctrine 2批量插入/更新内存

时间:2014-02-10 16:02:00

标签: php symfony memory doctrine-orm memory-leaks

考虑这段代码(包含在函数中):

    $manager = $this->manager; // local ref
    $q = $manager->createQuery('select c from VendorFeedBundle:Category c');
    $iterableResult = $q->iterate();
    $i = 0;
    $batchSize = 500;

    foreach($iterableResult as $row) {
        $category = $row[0];

        $struct = explode(' ' . $this->separator . ' ', $category->getPath());
        unset($struct[count($struct) - 1]);
        $path = implode(' ' . $this->separator . ' ', $struct);

        if (!$parent = $this->repo->findOneBy(['path' => $path])) {
            continue;
        }

        $category->setParent($parent);

        // flush every x entities
        if (($i % $batchSize) == 0) {
            echo 'Flushing batch...' . "\n";
            echo 'Memory: ' . $this->getReadableSize(memory_get_usage()) . "\n";

            $manager->flush();
            $manager->clear();

            echo 'After batch...' . "\n";
            echo 'Memory: ' . $this->getReadableSize(memory_get_usage()) . "\n";
        }
        ++$i;
    }

    // flush the remaining
    $manager->flush();
    $manager->clear();

它在我的终端中记录以下内容:

Creating tree...
Memory: 14.91 MB
Flushing batch...
Memory: 18.46 MB
After batch...
Memory: 18.79 MB
Flushing batch...
Memory: 21.01 MB
After batch...
Memory: 23.29 MB
Flushing batch...
Memory: 25.36 MB
After batch...
Memory: 27.87 MB
Flushing batch...
Memory: 29.88 MB
.... etc

getReadAbleSize方法不会将任何变量泄漏到全局范围或任何内容。 我已阅读并遵循有关doctrine2批量插入/更新(批处理)的建议: http://docs.doctrine-project.org/en/latest/reference/batch-processing.html

我做错了什么? 每500件物品增加3~4 MB内存似乎是对我的一点点泄漏。

旁注:我需要以这种方式更新项目,因为我的系统分为2个进程;首先我插入类别,然后更新父关系。

我的类别类是一个基本的Doctrin2实体,其中添加了一些Gedmo扩展(树,可翻译,时间戳) 请参阅:http://pastie.org/private/oiiyf54zjuouhiqjsjislg

我的完整脚本(迭代和更新类别): http://pastie.org/private/k5x240vr4taepczhqa4tva

1 个答案:

答案 0 :(得分:2)

  1. 将SQL记录器设置为空
  2. $em->getConnection()->getConfiguration()->setSQLLogger(null);

    1. gc_collect_cycles()
    2. 之后手动调用函数$em->clear()

      $em->clear(); gc_collect_cycles();

      不要忘记将zend.enable_gc设置为1,或在使用gc_enable()之前手动拨打gc_collect_cycles()

      1. 如果从控制台运行命令,请添加--no-debug选项。