Last time we talked about RefCount and Is_ref, here's a memory leak.
Copy Code code as follows:
$a = Array (1, 2, & $a);
unset ($a);
in the old version of PHP, there will be a memory leak, the analysis is as follows:
To perform the first line, you can know that $a and $a[2] point to the Zval refcount=2,is_ref=1
Then execute the second line, $a will be removed from the symbol table, pointing to the Zval refcount--, Refcount=1, because refcount!=0, so zval will not be used as garbage collection, but at this time we have lost $a[2] Point to the entrance to this zval, so this zval into a piece of memory garbage
The same can happen in a class internal reference, such as
Copy Code code as follows:
$a = new Man ();
$a->self = & $a;
unset ($a);
So how to solve this problem, the new GC mechanism uses an algorithm to solve this problem
PHP has a root buffer for storing Zval node information, when the root buffer is full or the GC function is manually invoked, the GC algorithm starts
For a zval of an array or class type, when the garbage collection mechanism starts, the algorithm iterates through the zval of the element/member within the Zval array/class and RefCount minus 1, if the zval is reduced to 0 after the traversal is completed, It means that this zval is a memory garbage that he will be destroyed, see the example below
Copy Code code as follows:
$a = Array (1, 2, & $a, & $a);
unset ($a);
Easy to know $a pointing zval, assuming Z1 refcount=3,is_ref=1
When unset ($a) executes, the $a has been deleted from the symbol table, and we have lost access to the Z1, at this time Z1 refcount=2,is_ref=1
When the GC is started, the Zval refcount of the Z1 array element is traversed to reduce 1, traversing to a[2] Z1 refcount--a[3, z1 refcount--when z1 = 0 to mark RefCount as memory garbage. Algorithm to reclaim it after
The