Table of Contents
The structure of zval
Memory leaks caused by circular references
The recycling process of object and array
Principle of Garbage Collection
Example
Home Backend Development PHP7 How to implement garbage collection mechanism in php7

How to implement garbage collection mechanism in php7

May 24, 2021 am 09:21 AM
php7 Garbage collection mechanism

This article will introduce to you how php7 implements the garbage collection mechanism. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How to implement garbage collection mechanism in php7

When understanding our php GC, I feel it is necessary for me to introduce the underlying implementation of our php variables.

The structure of zval

// php 变量对于的c结构体
struct _zval_struct {
    zend_value value;
    union {
       ……
    } u1;
    union {
        ……
    } u2;
};
Copy after login

Since it mainly talks about garbage collection, here is a brief introduction to the functions of the u1 u2 union
The structure of u1 is more complicated. I think it is mainly used to identify variables. Type
u2 Most of them are auxiliary fields, the implementation of internal functions of variables, improving cache friendliness, etc.
Next is our protagonist

zend_value, which is also embedded in the structure. Union

typedef union _zend_value {
    zend_long         lval;//整形
    double            dval;//浮点型
    zend_refcounted  *counted;//获取不同类型的gc头部
    zend_string      *str;//string字符串
    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 {
        ZEND_ENDIAN_LOHI(
            uint32_t w1,
            uint32_t w2)
    } ww;
} zend_value;
Copy after login

records the type of reference count zend_refcounted *counted in the value of zval. Our garbage collection mechanism is also based on this.

typedef struct _zend_refcounted_h {
    uint32_t         refcount;          /* reference counter 32-bit */
    union {
        struct {
            ZEND_ENDIAN_LOHI_3(
                zend_uchar    type,
                zend_uchar    flags,    /* used for strings & objects */
                uint16_t      gc_info)  /* keeps GC root number (or 0) and color */
        } v;
        uint32_t type_info;
    } u;
} zend_refcounted_h;
Copy after login

All complex type definitions start with the zend_refcounted_h structure. In addition to reference counting, this structure also has GC-related structures. Therefore, when doing GC recycling, the GC does not need to care about the details. What is the type? All of them can be treated as zend_refcounted* structures.
#Automatic recycling of variables

In PHP, except for array and object type variables, most of the others are automatically recycled
The recycling of PHP ordinary variables is related to the number of references to the variable.

Official example

$a = 1;
$b = $a;
xdebug_debug_zval('a');
$a =10;
xdebug_debug_zval('a');
unset($a);
xdebug_debug_zval('a');
Copy after login

Result

a:
(refcount=2, is_ref=0),int 1
a:
(refcount=1, is_ref=0),int 10
a: no such symbol
Copy after login

You can see that when $a =10, the COW (copy-on-write) mechanism of php is involved, $b A copy of the original $a will be copied, and the reference relationship between them will be released, so the number of references (refcount) of a is reduced to 1.

Then the number of references to a becomes 0 after we uset($a). This will be considered a garbage variable and free up space.

Another example

$a = [1];
$a[1] = &$a;
unset($a);
Copy after login

The type of $a before unset($a) is a reference type

a:
(refcount=2, is_ref=1),
array (size=2)
  0 => (refcount=1, is_ref=0),int 1
  1 => (refcount=2, is_ref=1),
    &array<
Copy after login

unset($ a) After that, it becomes like this

At this time, when we unset the refcount changes from 2 to 1, because there is an internal reference pointing to $a, so where it is externally The occupied space will not be destroyed.

Then our external reference has been broken and we can't use it. It becomes an "orphan", which is called a wild pointer in the C language. In php it's called a circular reference. Memory leak. If you want to destroy the variable, you can only wait for the php script to end.

Memory leaks caused by circular references

In order to clean up these garbage, two guidelines are introduced

  • If the reference count is reduced to zero, the variable container is Will be cleared (free) and is not garbage

  • If the reference count of a zval is still greater than 0 after being reduced, then it will enter the garbage cycle. Secondly, during a garbage cycle, find out which parts are garbage by checking whether the reference count is reduced by 1 and checking which variable containers have zero references.

Circular references basically only appear in arrays and objects. The object is because it itself is a reference

The recycling process of object and array

php7's garbage collection consists of two parts, one is the garbage collector and the other is the garbage collection algorithm.

The garbage collector collects the elements just mentioned that may be garbage into the recycling pool, that is, the variables with zend_refcount>0 are placed in the recycling pool. When the value of the recycling pool reaches a certain amount, it will be traversed uniformly. Perform simulated deletion. If zend_refcount=0, it is considered garbage and deleted directly.

Traverse every variable in the recycling pool, and then traverse each member based on each variable. If the members are still nested, continue traversing. Then set the simulated refcount of all members to -1. If the reference count of the external variable is 0 at this time. Then it can be considered garbage, clearly. If it is greater than 0, then the number of references is restored and taken out from the garbage collection pool.

Principle of Garbage Collection

If your variable is not garbage, then after the references of all its member variables are reduced by one, the reference of the total variable will definitely not be 0.

Example

It’s rather hard to say, so why not give an example. When I first browsed sf.gg, I saw a question about GC, and I answered it. About the GC garbage collection mechanism

The topic is as follows
How to implement garbage collection mechanism in php7

//我的回答
1、只要zval.value的refcount减一,然后缺其refcount的值不为0那么它就可能是垃圾,进入垃圾周期。
2、进入垃圾池遍历所有成员,包括其嵌套的成员,都对其做 refcount-1的操作,看外部的引用是否为0。

那么对于 题主的问题来说,
首先,你要想$a为垃圾,一定要先对 unset($a)操作,那么此时 $a的 refcount = 2
对于$a[0] refcount-1 不影响外部的$a,
$a[1] refcount-1 ,此时 $a的 refount=1
$a[2] refcount-1 ,此时 $a 的 refount=0 
模拟减结束,那么此变量被当成垃圾回收。
Copy after login

Recommended study:php video tutorial

The above is the detailed content of How to implement garbage collection mechanism in php7. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if the plug-in is installed in php7.0 but it still shows that it is not installed? What should I do if the plug-in is installed in php7.0 but it still shows that it is not installed? Apr 02, 2024 pm 07:39 PM

To resolve the plugin not showing installed issue in PHP 7.0: Check the plugin configuration and enable the plugin. Restart PHP to apply configuration changes. Check the plugin file permissions to make sure they are correct. Install missing dependencies to ensure the plugin functions properly. If all other steps fail, rebuild PHP. Other possible causes include incompatible plugin versions, loading the wrong version, or PHP configuration issues.

How to solve the problem when php7 detects that the tcp port is not working How to solve the problem when php7 detects that the tcp port is not working Mar 22, 2023 am 09:30 AM

In php5, we can use the fsockopen() function to detect the TCP port. This function can be used to open a network connection and perform some network communication. But in php7, the fsockopen() function may encounter some problems, such as being unable to open the port, unable to connect to the server, etc. In order to solve this problem, we can use the socket_create() function and socket_connect() function to detect the TCP port.

How to install mongo extension in php7.0 How to install mongo extension in php7.0 Nov 21, 2022 am 10:25 AM

How to install the mongo extension in php7.0: 1. Create the mongodb user group and user; 2. Download the mongodb source code package and place the source code package in the "/usr/local/src/" directory; 3. Enter "src/" directory; 4. Unzip the source code package; 5. Create the mongodb file directory; 6. Copy the files to the "mongodb/" directory; 7. Create the mongodb configuration file and modify the configuration.

PHP Server Environment FAQ Guide: Quickly Solve Common Problems PHP Server Environment FAQ Guide: Quickly Solve Common Problems Apr 09, 2024 pm 01:33 PM

Common solutions for PHP server environments include ensuring that the correct PHP version is installed and that relevant files have been copied to the module directory. Disable SELinux temporarily or permanently. Check and configure PHP.ini to ensure that necessary extensions have been added and set up correctly. Start or restart the PHP-FPM service. Check the DNS settings for resolution issues.

An article to talk about the garbage collection mechanism in php An article to talk about the garbage collection mechanism in php Aug 26, 2022 am 10:48 AM

This article will give you an in-depth understanding of the garbage collection mechanism in PHP. I hope it will be helpful to you!

How to install and deploy php7.0 How to install and deploy php7.0 Nov 30, 2022 am 09:56 AM

How to install and deploy php7.0: 1. Go to the PHP official website to download the installation version corresponding to the local system; 2. Extract the downloaded zip file to the specified directory; 3. Open the command line window and go to the "E:\php7" directory Just run the "php -v" command.

Decrypting the memory management and garbage collection mechanism of Go language Decrypting the memory management and garbage collection mechanism of Go language Nov 30, 2023 am 09:17 AM

Go language is an efficient, safe, and concurrent programming language. The design of memory management and garbage collection mechanism is also its unique feature. This article will decrypt the memory management and garbage collection mechanism of Go language in depth. 1. Memory management In the Go language, memory management includes two aspects: memory allocation and memory release. 1.1 Memory allocation In the Go language, we allocate memory through the built-in functions new and make. Among them, new returns a pointer to the newly allocated zero value, while make returns a specified type and its length.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

See all articles