Basic knowledge of reference counting The official website’s answer is as follows
Each PHP variable exists in a variable container called "zval"
A zval variable container, in addition to the type and value of the variable, also includes two bytes of additional information is_ref
and refcount
is_ref
is a bool value used to identify whether this variable belongs to a reference set. Through this byte, the PHP engine can distinguish ordinary variables from reference variables
refcount
Used to represent the number of variables pointing to this zval variable container
Reference counting in PHP5
In PHP5, zval memory is allocated separately from the heap (heap) (With a few exceptions), PHP needs to know which zvals are in use and which ones need to be freed. So this requires the use of reference counting: the value of refcount__gc in zval is used to save the number of times zval itself is referenced, such as
b = 12 statement, 12 is referenced by two variables, so its reference count is 2. If the reference count becomes 0, it means that the variable is no longer used and the memory can be released.
As follows
<?php //php zval变量容器$a = 1;$b = 1;$c = &$a;$d = $b;$e = range(0, 3); xdebug_debug_zval('a'); xdebug_debug_zval('b'); xdebug_debug_zval('c'); xdebug_debug_zval('d'); xdebug_debug_zval('e'); >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 结果如下 a:(refcount=2, is_ref=1),int 1b:(refcount=2, is_ref=0),int 1c:(refcount=2, is_ref=1),int 1d:(refcount=2, is_ref=0),int 1e:(refcount=1, is_ref=0), array (size=4) 0 => (refcount=1, is_ref=0),int 0 1 => (refcount=1, is_ref=0),int 1 2 => (refcount=1, is_ref=0),int 2 3 => (refcount=1, is_ref=0),int 3
Each variable has its own number
zval## in PHP7
#In PHP7, zval has a new implementation. The most basic change is that the memory required by zval is no longer allocated separately from the heap, andno longer stores the reference count by itself. The reference count of complex data types (such as strings, arrays, and objects) is stored by itself. This implementation has the following benefits:
<?php //php zval变量容器$a = 1;$b = 1;$c = &$a;$d = $b;$e = range(0, 3); xdebug_debug_zval('a'); xdebug_debug_zval('b'); xdebug_debug_zval('c'); xdebug_debug_zval('d'); xdebug_debug_zval('e'); >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 结果如下 a:(refcount=2, is_ref=1)int 1b:(refcount=0, is_ref=0)int 1c:(refcount=2, is_ref=1)int 1d:(refcount=0, is_ref=0)int 1e:(refcount=1, is_ref=0)array (size=4) 0 => (refcount=0, is_ref=0)int 0 1 => (refcount=0, is_ref=0)int 1 2 => (refcount=0, is_ref=0)int 2 3 => (refcount=0, is_ref=0)int 3
The above is the detailed content of Master the php garbage collection mechanism. For more information, please follow other related articles on the PHP Chinese website!