【问题标题】:Symfony task - memory leakSymfony 任务 - 内存泄漏
【发布时间】:2012-07-05 04:20:14
【问题描述】:

我写了一个 symfony 任务来填充样本数据的数据库。这是一段示例代码:

gc_enable();
Propel::disableInstancePooling();

public function test()
{
    for($i = 0; $i < 10000; $i++) {
        $this->doIt($i);
    }
}

public function doIt($i)
{
    $user = new User();
    $user->setUsername('user' . $i . "@example.com");
    $user->setPassword('test');
    $user->setFirstName('firstname' . $i);
    $user->setLastName('surname' . rand(0, 1000));

    $user->save();
    $user->clearAllReferences(true);
    $user = null;
    gc_collect_cycles();
}

如何限制内存的使用?

【问题讨论】:

标签: php memory-leaks symfony1 propel


【解决方案1】:

symfony CLI 任务需要相当多的 PHP 内存,尤其是在 Windows 上。如果 Propel 任务失败,我建议将内存分配的 php.ini 文件设置永久更改为至少 256M。我知道这看起来很高,但您应该只需要在开发机器上完成这些任务。

【讨论】:

    【解决方案2】:

    an other thread on SO 有一些不错的提示。

    这是一篇关于memory leak using propel 的非常好的博文。是法语的,但真的很有趣。

    而且,如果您正在处理大数据(例如批量导入),您还应该看看 pcntl_fork (see this gist)。 pcntl_fork 在 Windows 上不起作用。我用这种方法来处理大的导入,它真的很快而且不会吃掉你所有的内存。

    【讨论】:

    • Danke,我使用了 Propel::disableInstancePooling();在错误的地方。它应该在方法内部。
    • 关于pcntl_fork,我写了一个小库来缓解使用它的痛苦:github.com/AZielinski/SimpleProcess
    【解决方案3】:

    这是最终代码。它可以在相同的内存使用级别下工作一段时间。谢谢大家。

    public function test()
    {
        for($i = 0; $i < 10000; $i++) {
            $this->doIt($i);
        }
    }
    
    public function doIt($i)
    {
        gc_enable();
        Propel::disableInstancePooling();
    
        $user = new User();
        $user->setUsername('user' . $i . "@example.com");
        $user->setPassword('test');
        $user->setFirstName('firstname' . $i);
        $user->setLastName('surname' . rand(0, 1000));
    
        $user->save();
        $this->delete($user);
    }
    
    public function delete($obj)
    {
        $obj->clearAllReferences(true);
        unset($obj);
        // redundant
        // gc_collect_cycles();
    }
    

    【讨论】:

    • 谢谢你,它也适用于我。但是,我注意到 gc_collect_cycles();不是必需的,但它会使代码运行得更慢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    相关资源
    最近更新 更多