views:

78

answers:

3

I have an array of objects. If I call unset($array), will it unset all objects in the array AND the array or just the array? Let's assume these objects are referenced nowhere else.

+2  A: 

If that array contains the only reference to the object, then yes. Otherwise no. Also, something to keep in mind from the PHP Documentation:

unset() does just what it's name says - unset a variable. It does not force immediate memory freeing. PHP's garbage collector will do it when it see fits - by intention as soon, as those CPU cycles aren't needed anyway, or as late as before the script would run out of memory, whatever occurs first.

GSto
A: 

It looks like the memory is not freed until your script finishes executing. http://bugs.php.net/bug.php?id=48368

bkuhns
Since you didn't specify what version you're using, I should note that the other answers here would be more appropriate if you're at version 5.3 or higher due to the introduction of the Garbage Collector. Without GC, however, your objects will remain in memory until your script is done executing.
bkuhns
I'm using 5.2.6.
Chad Johnson
+1  A: 

GSto is right... Only the PHP garbadge collector can free memory. unset() a variable or setting it to NULL can speed up the "garbadge collecting" process (at price of CPU cycles) but there is no way to directly free some memory (à la C++ where "delete" will actually free the memory).

I asked a similar question some time ago on a forum and this is what I got:

From Fou-Lu @ codingforums.com:

Unset free's its resources, and any free request does the same (like mysql_free_result). Yes, this allows the collector to take care of it. But until the collection process occurs, it will ignore any referenced variables. So, if a pass of the gc sees that a variable is referenced, it will ignore it. If it sees that it has been freed, it will take it, but if you have a block of data that is not freed and not used than it will sit in memory until script termination (less relevant nowadays on modern high ram systems). Using unset on an array is sufficient for the gc to take it. I'll see if I can find it in the source, but I would presume that all HashMaps used by the C reference pointers and not values, so the values themselves are not of any relevance since a null pointer is the same size anyway. I'd also suspect that once the GC gets to the hashmap that it will go through and release every zval associated with it and will perform write-on-copy for any individual pointer associated with a particular variable (fancy way of saying that it won't release any index that is referenced by another variable).

http://www.codingforums.com/showthread.php?t=184164

AlexV