Does calling unset()
free t开发者_Go百科he 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).
Does calling unset() free the memory that was associated with that object?
Yes it does.
Check for yourself using memory_get_usage()
:
echo memory_get_usage() . "<br />";
unset($array['key']);
unset($array['key2']);
unset($array['key3']);
echo memory_get_usage();
More Resources:
- Garbage Collection (Offical Docs but for 5.3)
- Be wary of garbage collection
Quoting from later link:
PHP performs garbage collection at three primary junctures:
- When you tell it to
- When you leave a function
- When the script ends
Situation 1 occurs when you use unset(), mysql_free_result(), or other resource-destroying functions that explicitly clear up after your variables. Situation 2 clears up resources implicitly - any variable that leaves scope, i.e. is no longer applicable, gets cleared up for you. Finally, situation 3 frees up all script-related resources implicitly.
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.
It doesn't free the memory immediately, but it allows the garbage collector to do it.
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
.
In PHP >5.3.0, the gc_collect_cycles() function forces collection of any existing garbage cycles.
精彩评论