Does calling unset()
free the memory that was associated with that object? There are a couple cases where I find myself handling large associative arrays and I would like to remove them when done (freeing up memory to create new ones).
views:
85answers:
6It doesn't free the memory immediately, but it allows the garbage collector to do it.
unset()
does "free" memory in php, but it lets the garbage collector decide when to actually release said memory. Thus, memory is freed on an as-needed or as-convenient basis (prior to PHP running out of available memory).
A major caveat is to watch that you're not attempting to unset()
global variables within a local scope. Even variables passed in by reference will only have their local references unset
when this is performed in a function's locale. To truly make memory available, any unset()
should be done in that variable's appropriate scope.
In PHP >5.3.0, the gc_collect_cycles() function forces collection of any existing garbage cycles.
By unsetting a variable you're setting it's "refcount" to 0. This allows for the Zend Engine to shift things about in memory and it knows that it can overwrite your variables area in memory as it has a refcount of 0.
This occurs before garbage collection is even thought of. So there you have it, unset() does actually help you out during the lifecycle of your app.
No, it doesn't necessarily free anything. It just decreases the reference count.
Example:
//object has reference count 1 because it has one variable referencing 1
$a = new BigObject;
//object still has reference count 2, but no new object was allocated in memory
$b = $a;
//object has reference count 1
unset($a);
//the object is still in memory
Nitpick corner: technically, there are two reference counts in play here -- the object's and the zval's. The reference count of the object is only 1 throughout the program, it's actually the reference count of the zval that's changed in the assignment and in the call to unset
.