search
HomeBackend DevelopmentPHP TutorialA brief discussion of PHP source code 33: Basics of the new garbage collection mechanism (Garbage Collection) added in PHP5.3

This article mainly introduces the basics of PHP source code thirty-three: the newly added garbage collection mechanism (Garbage Collection) of PHP5.3. It has a certain reference value. Now I share it with you. Friends in need can refer to it. Let’s talk about

33 of PHP source code: The basics of the new garbage collection mechanism (Garbage Collection) in PHP5.3
The garbage collection mechanism is newly added in PHP5.3, which is said to be very advanced. That said seduced me to see its advanced implementation.
For the official documentation, please click Garbage Collection
Chinese version address: http://docs.php.net/manual/zh/features.gc.php
[Embedding method of garbage collection mechanism]## The #zend_gc.h file is referenced at line 749 of zend.h: #include "zend_gc.h"
Thus replacing the ALLOC_ZVAL and other macros in the zend_alloc.h file referenced at line 237
zend/zend_gc. h file starts at line 202

 /* The following macroses override macroses from zend_alloc.h */#undef  ALLOC_ZVAL#define ALLOC_ZVAL(z) \
do {\
(z) = (zval*)emalloc(sizeof(zval_gc_info));\
GC_ZVAL_INIT(z);\
} while (0)

The definition of ALLOC_ZVAL macro in zend_alloc.h is to allocate the memory space of a zval structure. The new ALLOC_ZVAL macro allocates a zval_gc_info structure macro. The structure of zval_gc_info is as follows:

zend/zend_gc.h file starts at line 91:

 typedef struct _zval_gc_info {
zval z;
union {
gc_root_buffer       *buffered;
struct _zval_gc_info *next;
} u;} zval_gc_info;

The first member of zval_gc_info is the zval structure, which ensures that it is aligned with the beginning of the memory allocated with the zval variable , so that it can be used as a zval when the zval_gc_info type pointer is cast. The gc_root_buffer, etc. will be introduced later in the structure and implementation. It defines the cache structure of the PHP garbage collection mechanism. GC_ZVAL_INIT is used to initialize zval_gc_info that replaces zval. It will set the buffered field of member u in zval_gc_info to NULL. This field will only have a value when it is put into the garbage collection buffer, otherwise it will always be NULL.

Since all variables in PHP exist in the form of zval variables, zval_gc_info is used here to replace zval, thereby successfully integrating the garbage collection mechanism in the original system.

This feels a bit like object-oriented polymorphism.

[Storage method of garbage collection mechanism]

Node structure:

 typedef struct _gc_root_buffer {
struct _gc_root_buffer   *prev;/* double-linked list               */
struct _gc_root_buffer   *next;
zend_object_handle        handle;/* must be 0 for zval               */
union {
zval                 *pz;
zend_object_handlers *handlers;
} u;} gc_root_buffer;

Obviously (see comments, although there are very few comments in PHP, some are purely tangled comments) , which is a doubly linked list.

The pz variable in the union is obviously the polymorphic zval_gc_info structure defined before, so its current node pointer in the linked list can be passed ((zval_gc_info*)(pz))->u .buffered, but looking at the source code, this calling method is used in many places, why not create a new macro? Is it because I am afraid of having too many macros? No, PHP is famous for having many macros, and there are many macros that have more nested macros than this one. don't know. In addition, handle and other structures are specifically targeted at object variables.

The buffer is in a global variable. Like the global variables of other modules, gc also has its own global variable access macro GC_G(v). Similarly, the global variable access macro is different under ZTS or not. realization.

The global variables defined in zend_gc.h are as follows:

typedef struct _zend_gc_globals {
zend_bool         gc_enabled;/* 是否开启垃圾收集机制 */
zend_bool         gc_active;/* 是否正在进行 */ 
gc_root_buffer   *buf;/* 预分配的缓冲区数组,默认为10000(preallocated arrays of buffers)   */
gc_root_buffer    roots;/* 列表的根结点(list of possible roots of cycles) */
gc_root_buffer   *unused;/* 没有使用过的缓冲区列表(list of unused buffers)           */
gc_root_buffer   *first_unused;/* 指向第一个没有使用过的缓冲区结点(pointer to first unused buffer)   */
gc_root_buffer   *last_unused;/* 指向最后一个没有使用过的缓冲区结点,此处为标记结束用(pointer to last unused buffer)    */ 
zval_gc_info     *zval_to_free;/* 将要释放的zval变量的临时列表(temporaryt list of zvals to free) */
zval_gc_info     *free_list;/* 临时变量,需要释放的列表开头 */
zval_gc_info     *next_to_free;/* 临时变量,下一个将要释放的变量位置*/ 
zend_uint gc_runs;/* gc运行的次数统计 */
zend_uint collected;    /* gc中垃圾的个数 */ // 省略...

[Color marking in the garbage collection mechanism]

 #define GC_COLOR  0x03 #define GC_BLACK  0x00#define GC_WHITE  0x01#define GC_GREY   0x02#define GC_PURPLE 0x03 #define GC_ADDRESS(v) \
((gc_root_buffer*)(((zend_uintptr_t)(v)) & ~GC_COLOR))#define GC_SET_ADDRESS(v, a) \
(v) = ((gc_root_buffer*)((((zend_uintptr_t)(v)) & GC_COLOR) | ((zend_uintptr_t)(a))))#define GC_GET_COLOR(v) \
(((zend_uintptr_t)(v)) & GC_COLOR)#define GC_SET_COLOR(v, c) \
(v) = ((gc_root_buffer*)((((zend_uintptr_t)(v)) & ~GC_COLOR) | (c)))#define GC_SET_BLACK(v) \
(v) = ((gc_root_buffer*)(((zend_uintptr_t)(v)) & ~GC_COLOR))#define GC_SET_PURPLE(v) \
(v) = ((gc_root_buffer*)(((zend_uintptr_t)(v)) | GC_PURPLE))

In PHP's memory management, we have also seen similar The last bit serves as some type of marking method.

Here, the last two digits of the memory allocation are used as the color mark of the entire structure. Among them,

white means garbage
purple means it has been put into the buffer
gray means that a refcount minus one operation has been performed
black is the default color, normal

[zval defined Change】

PHP3.0 version is in the zend/zend.h file, which is defined as follows:

struct _zval_struct {
/* Variable information */
zvalue_value value;/* value */
zend_uint refcount__gc;
zend_uchar type;/* active type */
zend_uchar is_ref__gc;};

In versions before php3.0, such as php5.2.9 version, it is in the zend/zend.h file , its definition is as follows:

struct _zval_struct {
/* Variable information */
zvalue_value value;/* value */
zend_uint refcount;
zend_uchar type;/* active type */
zend_uchar is_ref;};

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

A brief discussion on PHP source code 32: emalloc/efree layer and heap layer in PHP memory pool

A brief discussion on PHP source code 31: The basics of the heap layer in the PHP memory pool

A brief discussion on PHP source code 30: PHP memory pool Storage layer in

The above is the detailed content of A brief discussion of PHP source code 33: Basics of the new garbage collection mechanism (Garbage Collection) added in PHP5.3. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools