daniels
daniels

Reputation: 19243

Does this cause a PHP memory leak?

Does this cause a PHP memory leak?

function xml_parse($xmlString)
{
    return json_decode(json_encode(new SimpleXMLElement($xmlString)), true);
}

Or do i need to unset the SimpleXML obj like this?

function xml_parse($xmlString)
{
    $sObj = new SimpleXMLElement($xmlString);
    $ret  = json_decode(json_encode($sObj), true);
    unset($sObj);
    return $ret;
}

I am running this in a large foreach as the script needs to parse lots of files.

Upvotes: 1

Views: 1619

Answers (3)

Rijk
Rijk

Reputation: 11301

If you really want to know, run it a couple thousand times and output the memory usage. Normally, unused objects will be cleaned up by the garbage collector, so the first snippet wouldn't 'leak' memory. However, in PHP <5.3 there is an issue with circular references which can prevent unused objects from being collected. So if you do experience an issue, updating PHP might solve it for you.

Upvotes: 2

Emil Vikstr&#246;m
Emil Vikstr&#246;m

Reputation: 91983

It will not cause a memory leak. PHP's garbage collector will see that there's no references left to the SimpleXMLElement and remove it as needed.

Upvotes: 1

Nexerus
Nexerus

Reputation: 1088

I'm no uber PHP guru, but I would probably go with the second example you have there, just to be safe.

Upvotes: 1

Related Questions