PHP是如何做垃圾回收的(图文)-php教程

资源魔 37 0

PHP是若何做渣滓收受接管的?

蕴含 php 5 与 php7 的变量完成以及渣滓收受接管的比照

变量的完成

PHP 的变量是弱类型的,能够示意整数、浮点数、字符串等类型。PHP 的变量是应用构造体 zval 示意的

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;
};

PHP5 与 PHP7 援用计数的比照

php 5.* 变量赋值等操作援用计数如图所示,正在倒数第二步,会构成一个轮回援用,而且正在 unset 操作之后,会孕育发生渣滓。

PHP 7 的计数放到了详细的 value 中,zval 没有存正在写时复制(写时候离)。

而且 PHP 7 的有一个专门的 zend_reference 用来示意援用。

垃圾回收.draw.io-PHP7

有了以上对于 PHP 变量存储的常识,咱们能够了解一下 PHP 是若何做渣滓收受接管的了。

甚么是渣滓

起首,咱们需求界说甚么是渣滓。

1. refcount 添加的没有是

2. refcount 等于0的没有是,这个会被间接肃清

3. refcount 缩小,而且没有等于0的才是渣滓

渣滓搜集

1. php7 要求数据类型是数组以及工具,而且 type_flag 是 IS_TYPE_COLLECTABLE

2. 不正在缓冲区中存正在过

3. 不被标志过

4. 标志为紫色,而且放到缓冲区中

收受接管算法

论文:https://researcher.watson.ibm.com/researcher/files/us-bacon/Bacon01Concurrent.pdf

PHP 5.3 版本和之后的版本

1. 将渣滓放到一个 root 池中

2. 当满 10000 个节点的时分进行渣滓收受接管

3. 遍历双向链表中的节点 refcount-1

4. 遍历双向链表将 refcount=0 的节点删除了,到free行列步队中

5. 对 refcount!=0 的 refcount+1

四色切换

以上就是PHP是若何做渣滓收受接管的(图文)的具体内容,更多请存眷资源魔其它相干文章!

标签: php php开发教程 php开发资料 php开发自学 垃圾回收

抱歉,评论功能暂时关闭!