包含 php 5 与 php7 的变量实现和垃圾回收的对比php
PHP 的变量是弱类型的,能够表示整数、浮点数、字符串等类型。PHP 的变量是使用结构体 zval 表示的node
PHP 5.* zval 和 zend_value 结构算法
struct _zval_struct { // 结构体 zvalue_value value; zend_uint refcount__gc; zend_uchar type; zend_uchar is_ref__gc; } typedef union _zvalue_value { // 联合体 long lval; double dval; struct { char *val; int len; } str; // 字符串 HashTable *ht; // 数组 zend_object_value obj; // 对象 zend_ast *ast; } zvalue_value;
PHP 7.0 zval 和 zend_value 结构数组
struct _zval_struct { union { zend_long lval; /* long value */ double dval; /* double value */ zend_refcounted *counted; zend_string *str; zend_array *arr; zend_object *obj; zend_resource *res; zend_reference *ref; zend_ast_ref *ast; zval *zv; void *ptr; zend_class_entry *ce; zend_function *func; struct { uint32_t w1; uint32_t w2; } ww; } value; union { struct { ZEND_ENDIAN_LOHI_4( zend_uchar type, /* active type */ zend_uchar type_flags, zend_uchar const_flags, zend_uchar reserved) /* call info for EX(This) */ } v; uint32_t type_info; } u1; union { uint32_t var_flags; uint32_t next; /* hash collision chain */ uint32_t cache_slot; /* literal cache slot */ uint32_t lineno; /* line number (for ast nodes) */ uint32_t num_args; /* arguments number for EX(This) */ uint32_t fe_pos; /* foreach position */ uint32_t fe_iter_idx; /* foreach iterator index */ } u2; };
php 5.* 变量赋值等操做引用计数如图所示,在倒数第二步,会造成一个循环引用,而且在 unset
操做以后,会产生垃圾。php7
PHP 7 的计数放到了具体的 value 中,zval 不存在写时复制(写时分离)。ui
而且 PHP 7 的有一个专门的 zend_reference
用来表示引用。.net
有了以上关于 PHP 变量存储的知识,咱们能够理解一下 PHP 是如何作垃圾回收的了。3d
首先,咱们须要定义什么是垃圾。code
论文:https://researcher.watson.ibm.com/researcher/files/us-bacon/Bacon01Concurrent.pdf对象
PHP 5.3 版本以及以后的版本