PHP memory leak
Consider an RSS feed read in as an SimpleXMLobject $rss.
What’s the difference between:
foreach ($rss->channel as $channel) {
...
}
and
$foo = $rss->channel;
foreach ($foo as $channel) {
...
}
Not much you would say, the first code example is shorter and more to the point. However when putting the scripts to work, (with a big rss file) we’ll soon see the difference.
Memory problem and a growing swap file
After a while the former example is causing a lot of disk activity and you will see your swap file grow and grow, at my computer it reached the maximum of 4 GB and off course it took ages for the script to finish.
And all that while the maximum memory usage for a script is set to 24MB in php.ini. Should run in a 1G computer you would say.
Well example 2 does but example 1 does not!
Is seems that iterating over an object-property in a foreach loop is troubled by a memory leak.
Solution
Example 2 is the workaround!
Conclusion
PHP 5.1 until 5.2 seem to suffer from this memory leak.
October 22nd, 2008 at 3:52 pm
Wow! Thanks for this tip. It was a pain to find a memleak in a script, but this entry helped a lot to locate where is that, and why. Hopefully in the next release of PHP they will fix it – it’s a really serious bug!
October 22nd, 2008 at 4:16 pm
Sorry, in our case, it was geoip_org_by_name of the maxmind module. In php 5.2.6 we don’t have problem with iterations on object elements.
February 17th, 2009 at 6:39 pm
Upgrade to latest version of PHP or report it on http://bugs.php.net. As a matter of fact, I’m pretty sure I fixed that bug.
Good luck
July 15th, 2009 at 6:30 pm
[…] php tips […]
September 6th, 2009 at 7:20 pm
In my XAMPP-Installation with PHP Version 5.2.4, there are no memory leak with this example.
June 11th, 2010 at 6:18 am
i love your blog,really nice
February 7th, 2011 at 12:00 am
Hey! I just saw one other message in another weblog that looked like this. How have you learnt all these items? That’s one cool post.
April 24th, 2011 at 10:27 pm
Would you say this is now fixed in the current release of php then? Trying to narrow down some leakage problems myself
March 9th, 2012 at 4:50 am
Julia, sistemas de servidores…
[…]My Beloved PHP » Blog Archive » PHP memory leak[…]…