I have the following code, which receives data from a database ( quite a lot ) and passes them to a function which is processing those data. Here's what the codes looks like.
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;
}
And that's the output.
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
The output with 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
Which seems to me, PHP does not free $data
, instead it is just putting it all on top? $feed
is just a string. Not very large. I can't see why that script is running out of memory. And why it doesn't free data.
You must use memory_get_usage() because memory_get_peak_usage() is the max memory used.
When you make an unset the memory is cleared, but if you have another copy of this var this copy remains in memory.
In your call to $p->process($data)
if data is not a object or array, will be copied. If the data is an array and you modify this in the process function, then will be copied too. Try passing by reference with a &.
I suggest you use xhprof extension to make a memory usage inspection. You can see the memory usage by function.