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.

9 Responses to “PHP memory leak”

  1. dH Says:

    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!

  2. dH Says:

    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.

  3. David Coallier Says:

    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

  4. Hummy: Php Memory Leak Says:

    […] php tips […]

  5. anyone Says:

    In my XAMPP-Installation with PHP Version 5.2.4, there are no memory leak with this example.

  6. nike tn Says:

    i love your blog,really nice

  7. Thomas Phillippes the DNA testing guy Says:

    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.

  8. Stuart Says:

    Would you say this is now fixed in the current release of php then? Trying to narrow down some leakage problems myself

  9. Julia, sistemas de servidores Says:

    Julia, sistemas de servidores…

    […]My Beloved PHP » Blog Archive » PHP memory leak[…]…

Categories
Archives
Links