search
HomeBackend DevelopmentPHP TutorialAn 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
phpGarbage collection mechanism

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

An article to talk about the garbage collection mechanism in php

1. Basic knowledge of reference counting

  • Each PHP variable has a variable called zval in the variable container.
  • A zval variable container, in addition to containing the type and value of the variable, also includes two bytes of additional information.
  • The first one is is_ref, which is a bool value used to identify whether this variable belongs to the reference collection. Through this byte, the PHP engine can distinguish ordinary variables from reference variables. Since PHP allows users to use custom references by using &, there is also an internal reference counting mechanism in the zval variable container to optimize memory usage.
  • The second extra byte is refcount, used to indicate the number of variables pointing to this zval variable container.
  • All symbols exist in a symbol table, in which each symbol has a scope, as do the main scripts (for example: scripts requested through the browser) and each function or method. Scope.

2. Generate zval container

  • When a variable is assigned a constant value, a zval variable container will be generated
  • If Xdebug is installed, you can view these two values ​​through xdebug_debug_zval()
<?php $a = "new string";
xdebug_debug_zval(&#39;a&#39;);
 
//结果
a: (refcount=1, is_ref=0)=&#39;new string&#39;

3. Increase the reference count of zval

  • Assigning one variable to another variable will increase the number of references
<?php $a = "new string";
$b = $a;
xdebug_debug_zval( &#39;a&#39; );

//结果
a: (refcount=2, is_ref=0)=&#39;new string&#39;

4. Reduce the zval reference count

    ##Use
  • unset() Can reduce the number of references
  • The variable container containing the type and value will be deleted from the memory
<?php $a = "new string";
$c = $b = $a;
xdebug_debug_zval( &#39;a&#39; );
unset( $b, $c );
xdebug_debug_zval( &#39;a&#39; );

//结果
a: (refcount=3, is_ref=0)=&#39;new string&#39;
a: (refcount=1, is_ref=0)=&#39;new string&#39;

5. Composite types zval container

    is different from scalar type values
  • Array and object type variables store their members or attributes in their own symbol tables
  • This means that the following example will generate three zval variable containers
  • The three zval variable containers are: a, meaning and number

<?php $a = array( &#39;meaning&#39; => 'life', 'number' => 42 );
xdebug_debug_zval( 'a' );

//结果
a: (refcount=1, is_ref=0)=array (
   'meaning' => (refcount=1, is_ref=0)='life',
   'number' => (refcount=1, is_ref=0)=42
)

6. Increase the reference count of the composite type

    Add an existing element to the array

<?php $a = array( &#39;meaning&#39; => 'life', 'number' => 42 );
$a['life'] = $a['meaning'];
xdebug_debug_zval( 'a' );

//结果
a: (refcount=1, is_ref=0)=array (
   'meaning' => (refcount=2, is_ref=0)='life',
   'number' => (refcount=1, is_ref=0)=42,
   'life' => (refcount=2, is_ref=0)='life'
)

7. Reduce the reference count of composite types

    Deleting an element in the array
  • is similar to deleting a variable from the scope .
  • After deletion, the "refcount" value of the container where the element in the array is located is reduced
<?php $a = array( &#39;meaning&#39; => 'life', 'number' => 42 );
$a['life'] = $a['meaning'];
unset( $a['meaning'], $a['number'] );
xdebug_debug_zval( 'a' );

//结果
a: (refcount=1, is_ref=0)=array (
   'life' => (refcount=1, is_ref=0)='life'
)

8. Special circumstances

    Things get interesting when we add an array itself as an element of this array
  • Same as above, calling unset on a variable will delete the symbol and the number of references in the variable container it points to Also minus 1

<?php $a = array( &#39;one&#39; );
$a[] = &$a;
xdebug_debug_zval( &#39;a&#39; );

//结果
a: (refcount=2, is_ref=1)=array (
   0 => (refcount=1, is_ref=0)='one',
   1 => (refcount=2, is_ref=1)=...
)

九、清理变量容器的问题

  • 尽管不再有某个作用域中的任何符号指向这个结构(就是变量容器),由于数组元素“1”仍然指向数组本身,所以这个容器不能被清除 。
  • 因为没有另外的符号指向它,用户没有办法清除这个结构,结果就会导致内存泄漏。
  • 庆幸的是,php将在脚本执行结束时清除这个数据结构,但是在php清除之前,将耗费不少内存。
  • 如果上面的情况发生仅仅一两次倒没什么,但是如果出现几千次,甚至几十万次的内存泄漏,这显然是个大问题

十、回收周期

  • 像以前的 php 用到的引用计数内存机制,无法处理循环的引用内存泄漏
  • 而在php 5.3.0 中使用同步算法,来处理这个内存泄漏问题
  • 如果一个引用计数增加,它将继续被使用,当然就不再在垃圾中。
  • 如果引用计数减少到零,所在变量容器将被清除(free)
  • 就是说,仅仅在引用计数减少到非零值时,才会产生垃圾周期
  • 在一个垃圾周期中,通过检查引用计数是否减1,并且检查哪些变量容器的引用次数是零,来发现哪部分是垃圾

十一、回收算法分析

  • 为避免不得不检查所有引用计数可能减少的垃圾周期
  • 这个算法把所有可能根(possible roots 都是zval变量容器),放在根缓冲区(root buffer)中(用紫色来标记,称为疑似垃圾),这样可以同时确保每个可能的垃圾根(possible garbage root)在缓冲区中只出现一次。仅仅在根缓冲区满了时,才对缓冲区内部所有不同的变量容器执行垃圾回收操作。看上图的步骤 A。
  • 在步骤 B 中,模拟删除每个紫色变量。模拟删除时可能将不是紫色的普通变量引用数减"1",如果某个普通变量引用计数变成0了,就对这个普通变量再做一次模拟删除。每个变量只能被模拟删除一次,模拟删除后标记为灰
  • 在步骤 C 中,模拟恢复每个紫色变量。恢复是有条件的,当变量的引用计数大于0时才对其做模拟恢复。同样每个变量只能恢复一次,恢复后标记为黑,基本就是步骤 B 的逆运算。这样剩下的一堆没能恢复的就是该删除的蓝色节点了,在步骤 D 中遍历出来真的删除掉

十二、性能考虑

  • 主要有两个领域对性能有影响
  • 第一个是内存占用空间的节省
  • 另一个是垃圾回收机制释放已泄漏的内存耗费的时间增加

十三、垃圾回收机制的结论

  • PHP中的垃圾回收机制,仅仅在循环回收算法确实运行时会有时间消耗上的增加。但是在平常的(更小的)脚本中应根本就没有性能影响。
  • 然而,在平常脚本中有循环回收机制运行的情况下,内存的节省将允许更多这种脚本同时运行在你的服务器上。因为总共使用的内存没达到上限。
  • 这种好处在长时间运行脚本中尤其明显,诸如长时间的测试套件或者daemon脚本此类

推荐学习:《PHP视频教程

The above is the detailed content of An article to talk about the garbage collection mechanism in php. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools