我有以下代码,它从数据库(非常多)接收数据并将它们传递给处理这些数据的函数。 这是代码的样子。
for($o=0; $o<$times; $o++)
{
echo "Before Data: ".memory_get_peak_usage().PHP_EOL;
$data = $u->getDataLimit($id, $market, ($o*5000));
echo "After Data: ".memory_get_peak_usage().PHP_EOL;
echo "Before Process: ".memory_get_peak_usage().PHP_EOL;
$feed.= $p->process($data, ($o*5000) , 0, 0);
echo "After Process: ".memory_get_peak_usage().PHP_EOL;
$data = null; // or unset($data) doesnt matter.
echo "After All: ".memory_get_peak_usage().PHP_EOL.PHP_EOL;
}
这就是输出。
Before Data: 9587976
After Data: 37969952
Before Process: 37969952
After Process: 70166880
After All: 70166928
Before Data: 70166928
After Data: 83876232
Before Process: 83876232
After Process: 118233752
After All: 118233752
Before Data: 118233752
After Data: 141275760
Before Process: 141275760
After Process: 178939696
After All: 178939696
Before Data: 178939696
After Data: 202189192
Before Process: 202189192
After Process: 242915840
After All: 242915840
Before Data: 242915840
PHP Fatal error: Allowed memory size of 262144000 bytes exhausted (tried to allocate 32 bytes) in /var/www/repricing/repricing/library/Zend/Db/Statement/Pdo.php on line 290
memory_get_usage()
的输出:
Before Data: 9476792
After Data: 37943024
Before Process: 37969952
After Process: 70182072
After All: 56630760
Before Data: 56630760
After Data: 83864432
Before Process: 83897400
After Process: 118242320
After All: 113905024
Before Data: 113905024
After Data: 141247528
Before Process: 141278200
After Process: 178989656
After All: 174954320
Before Data: 174954320
After Data: 202216704
Before Process: 202251672
After Process: 243004472
After All: 241208824
Before Data: 241208824
PHP Fatal error: Allowed memory size of 262144000 bytes exhausted (tried to allocate 95 bytes) in /var/www/repricing/repricing/library/Zend/Db/Statement/Pdo.php on line 290
在我看来,PHP不会免费$data
,而只是将它全部放在首位?
$feed
只是一个字符串。不是很大。
我不明白为什么那个脚本内存不足。为什么它不会释放数据。
答案 0 :(得分:5)
您必须使用memory_get_usage(),因为memory_get_peak_usage()是使用的最大内存。
当您取消设置时,内存被清除,但如果您有此var的另一个副本,则此副本将保留在内存中。
在您对$p->process($data)
的调用中,如果数据不是对象或数组,则会被复制。如果数据是一个数组,并且您在过程函数中修改了它,那么也将被复制。使用&amp ;.尝试passing by reference
我建议你使用xhprof扩展来进行内存使用检查。您可以按功能查看内存使用情况。