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.
-
Let's assume you tried it. What happened?GZipp– GZipp2010-01-22 18:02:43 +00:00Commented Jan 22, 2010 at 18:02
-
Well, when I print_r($array) after calling unset(), nothing prints. So I'm not sure whether just the array OR the array and the objects it contains were freed.Chad Johnson– Chad Johnson2010-01-22 18:35:14 +00:00Commented Jan 22, 2010 at 18:35
3 Answers
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.
Comments
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).
Comments
It looks like the memory is not freed until your script finishes executing. http://bugs.php.net/bug.php?id=48368