Search code examples
phpmemory-managementunset

Use unset() to save memory


Background: I need to parse some large XML files line by line and save the infos in associative arrays. I'm parsing it with DOMDocument.

Even the memory saving not being an essential requirement, I'm trying to use the unset() to save some memory during my script execution to avoid any possible error of this type without use ini_set approaches and things like this.

See the code below to see my approach to do this:

        //using DOMDocument to get the tag product
        $countriesCovered = array();
        $countriesCoveredTag = $productTag->getElementsByTagName('countriesCovered')->item(0);
        $countries = $countriesCoveredTag->getElementsByTagName('country');
        foreach ($countries as $countryTag) {
            $country = array();
            $country['name'] = $countryTag->getElementsByTagName('name')->item(0)->nodeValue;
            $country['code'] = $countryTag->getElementsByTagName('code')->item(0)->nodeValue;
            $countriesCovered[] = $country;
            unset ($country);
        }

To me, it's logical that I'm saving memory doing this, since I'm copying the variable country to the array countriesCovered and unset country (I mean freeing memory that was allocated to country, right?). However, I didn't found anything to ensure this in the Documentation, so I can't ensure that I'm really saving memory.

Thus, Am I doing this in the right way? Is it needed even with the Garbage Collection? I think that perhaps the unset might be totally worthless, but I can't ensure this.


Solution

  • You can do this without temporary variable

    $countriesCovered[] = [
        'name' => $countryTag->getElementsByTagName('name')->item(0)->nodeValue,
        'code' => $countryTag->getElementsByTagName('code')->item(0)->nodeValue
    ]