Archive for November, 2007

PHP memory leak

Wednesday, November 28th, 2007

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.

Your are browsing
the Archives of My Beloved PHP for November 2007.
Categories
Archives
Links