2012-07-04 34 views
1

我寫了一個symfony任務來填充示例數據的數據庫。以下是一段代碼示例: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(); 
} 

如何限制內存的使用?

+0

可能重複http://stackoverflow.com/questions/2097744/php-symfony-doctrine-memory-leak – j0k

回答

0

您在an other thread on SO中有一些好的提示。

這裏是一個非常好的博客文章memory leak using propel。這是法文,但它真的很有趣。

而且,如果您正在處理大數據(例如批量導入),則還應該查看pcntl_fork(see this gist)。 pcntl_fork在Windows上不起作用。我使用這種方法來處理大量進口,而且速度非常快,並且不會吃掉所有的記憶。

+1

丹科,我用的Propel :: disableInstancePooling( );在錯誤的地方。它應該是內部方法。 –

+0

關於pcntl_fork,我寫了一個小型庫來緩解使用它的痛苦:https://github.com/AZielinski/SimpleProcess – adamziel

0

symfony CLI任務需要相當多的PHP內存,特別是在Windows上。如果Propel任務失敗,我會建議永久更改內存分配的php.ini文件設置爲至少256M。我知道這似乎很高,但你應該只在開發機器上需要這些任務。

+1

'$ PHP -r memory_limit的= -1' – hakre

3

這是最終的代碼。它可以在相同的內存使用級別下工作很長時間。 Thx大家。

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(); 
} 
+0

感謝你的這一點,它也適用於我。不過,我注意到gc_collect_cycles();沒有必要,但它會使代碼運行速度變慢。 – Aston