The 1.PHP garbage collection mechanism mainly uses the concept of reference counting.
When each variable is generated, it exists in a variable container called "Zaval". A Zval variable container that includes two bytes of extra information in addition to the type and value of the variable. The first is "Is_ref", which is a bool value that identifies whether the variable belongs to a reference collection (reference set). With this byte, the PHP engine can differentiate between normal and reference variables, and since PHP allows users to use the custom reference by using &, there is an internal reference counting mechanism in the Zval variable container to optimize memory usage. The second extra byte is "RefCount", which represents the number of variables (also known as symbols) that point to the Zval variable container. When Refcount=0, the garbage collection is started and the variable is destroyed.
For example:
<?php
$a = "new string";
?>
If Xdebug is turned on, you can use the Xdebug_debug_zval () function to display values for Is_ref and RefCount.
<?php
Xdebug_debug_zval (' a ');
?>
Output: A: (Refcount=1, is_ref=0) = ' new String '
Assigning a variable to another variable increases the number of references (refcount).
PHP does not replicate the generated variable container when it is not necessary. The variable container is destroyed when "RefCount" becomes 0 o'clock. When any variable associated to a variable container leaves its scope (for example, the function execution ends), or the function unset () is called on the variable, "RefCount" is reduced by 1.
When considering composite types such as array and object, things are a little bit more complicated. Unlike scalar (scalar) type values, variables of array and type object have their members or properties present in their own symbol table. This means that the following example will generate three Zval variable containers.
<?php
$a = array (' meaning ' + = ' life ', ' number ' = 42);
Xdebug_debug_zval (' a ');
?>
Output:
A: (Refcount=1, is_ref=0) =array (
' Meaning ' = (refcount=1, is_ref=0) = ' life ',
' Number ' = (refcount=1, is_ref=0) =42
)
Deleting an element in an array is similar to removing a variable from the scope. After deletion, the "refcount" value of the container in the array is reduced, similarly, when "RefCount" is 0 o'clock, the variable container is removed from memory.
PHP garbage collection mechanism