6

Should I always unset objects after using them? Consider the following code.

foreach ( $items as $item_id )
{
    $item = new Item($item_id);
    echo $item->name;
    unset( $item ); 
}

Is it advisable to use unset() this way? Are there better techniques to free up memory after using objects?

Dave
  • 3,328
  • 7
  • 26
  • 30

3 Answers3

4

In your case, no. Everytime $item is replace the old value is destroyed. The last value of $item will remain allocated, but if your code is well structured you'll be using functions and when $item goes out of scope it will finally be destroyed.

Artefacto
  • 96,375
  • 17
  • 202
  • 225
  • Is there a precise way to find how many class instances you can have per script execution? I'm just very skeptical about instantiating classes particularly within loops. – Dave Nov 25 '11 at 00:09
  • @Dave The thing you should worry about is memory. In any case, loops like yours are not a problem because the variable is being replaced on every iteration. – Artefacto Nov 25 '11 at 00:16
  • However, they say that rewriting the variable's data can also lead to longer execution time. http://stackoverflow.com/questions/584960/whats-better-at-freeing-memory-with-php-unset-or-var-null – Dave Nov 25 '11 at 00:26
  • 1
    @Dave Well, they're different things, but unless we're using references and don't want the side effects of writing to a reference, then just rewriting a variable is better than unset followed by recreating the variable. – Artefacto Nov 25 '11 at 01:16
2

Always? No. PHP has a garbage collector which will take care of removing objects from memory once they are not being used any longer.

  • What is the trigger point? Is it the end of the script or is there a timer that tells the system to automatically destroy the object after being unused for a certain period? – Dave Nov 25 '11 at 00:06
  • @Dave: Depending on how much memory is being used by the process, the garbage collector may run several times during the script's life time, or only at the end when the process is closing. –  Nov 25 '11 at 00:08
  • 1
    it's explained here. http://www.php.net/manual/en/features.gc.refcounting-basics.php – Emir Akaydın Nov 25 '11 at 00:09
1

No it is not necessery with PHP because objects are automatically destructed at the end of the process.

Emir Akaydın
  • 5,708
  • 1
  • 29
  • 57
  • But perhaps sometimes it's useful to release allocated memory if it's big and the script will take time to execute? – Dor Nov 25 '11 at 01:06
  • How big is big? It's usually difficult to decide when to explicitly unset an object. – Dave Nov 25 '11 at 01:32
  • @Dor: I'm using PHP since the first version released and never come up with a situation like that but yes, in very special conditions, unset() can be useful. I remember using isset()/unset() for session/global variables many years ago but I don't use them anymore if not necessery. – Emir Akaydın Nov 25 '11 at 01:47