Briefly describe the garbage collection mechanism of PHP

Brief description: Variables in php are stored in the variable container zval (c structure). In addition to storing variable types and values, zval also has is_ref and refcount fields. refcount indicates the number of elements pointing to the variable, and is_ref indicates whether the variable has an alias. If the refcount of a zval increases, it will continue to be used, and of course it is not garbage. If the refcount is reduced to 0, the variable container is recycled, which is a normal release, not garbage. If the refcount of a zval is reduced to non-zero (here contains the circular referenced zval), it may be garbage, and it will enter the garbage buffer. When the buffer reaches the maximum value, the recovery algorithm will loop through the zval, determine whether it is garbage, and release it. To solve the problem of memory leaks caused by circular references

 

Memory leak: The memory is applied for during the running of the program, but it is not released in time after the use is completed

 

Memory leak caused by circular references: When an array or object internal child element references its parent element, and if its parent element is deleted at this time, the variable container will not be deleted, because its child element is still pointing to the variable container, refcount> 0, but because there is no symbol pointing to the variable container, it cannot be manually cleared, so a memory leak will occur until the end of the script execution

$a = array( 'one' );
$a[] = &$a;
unset($a);

 

Garbage collection algorithm: Whenever the buffer is full, PHP will "simulate delete" all zval traversals in the buffer, and then perform "simulated recovery" or "really delete". However, PHP will only restore the zval with refcount> 0 after the simulated deletion, and the zval that has not been restored, that is, refcount = 0, is garbage, and it is deleted for real. Simulated deletion simply means performing a refcount minus 1 operation for each element in this zval. After the operation is completed, if the refcount of the zval=0, then this zval is garbage. Simulated recovery is equivalent to the inverse operation of simulated deletion

Guess you like

Origin blog.csdn.net/weixin_38230961/article/details/106232073