Problems related to PHP garbage collection mechanism

Source: Internet
Author: User
Tags php language
This article mainly introduces the PHP garbage collection mechanism related questions, the interest friend's reference, hoped to be helpful to everybody.

basic GC Concepts for PHPThe PHP language, like other languages, has a garbage collection mechanism. So today we are going to explain to you about the PHP garbage collection mechanism of related issues. We hope to help you. PHP strtotime Application Experience PHP memory_get_usage () Management memory PHP unset global variables to use the problem in detail PHP unset () function destroy variables teach you to quickly implement PHP full-site permissions verification, PHP garbage collection mechanism ( Garbage Collector referred to as GC) in PHP, when no variable points to this object, the object becomes garbage. PHP will destroy it in memory, which is the GC garbage disposal mechanism of PHP to prevent memory overflow. When a PHP thread ends, all memory space currently occupied is destroyed, and all objects in the current program are destroyed at the same time. The GC process usually starts with each session. The GC is designed to automatically destroy deleted files after the session file expires. Second, __destruct/unset __destruct () destructors are executed when the garbage object is reclaimed.
Unset destroys a variable that points to an object, not the object. Third, Session and PHP garbage collection mechanism because of PHP's working mechanism, it does not have a daemon thread to periodically scan the Session information and determine whether it is invalid, when a valid request occurs, PHP will be based on the global variable session.gc_ Probability and Session.gc_pisor values to determine whether a GC is enabled, by default, Session.gc_probability=1, Session.gc_pisor = 100 that is 1% possibility to start GC (That is, only one GC in 100 requests starts with one of the 100 requests). PHP garbage collection mechanism is to scan all the session information, with the current time minus the last time the session was modified, compared with the session.gc_maxlifetime parameter, if the survival time exceeds gc_maxlifetime (default 24 minutes ), the session is deleted.
However, if your Web server has multiple sites, multiple sites, GC processing sessions can have unexpected results because the GC does not differentiate between sessions at different sites at work. So how do you solve this?
1. Modify Session.save_path, or use Session_save_path () to save each site's session to a dedicated directory,
2. Provide GC start rate, naturally, PHP garbage collection mechanism to improve the start rate, the system performance will be correspondingly reduced, not recommended.
3. Determine the lifetime of the current session in the code and delete it using Session_destroy ().


Reference Counting Basics There is a variable container called "Zval" for each PHP variable. A zval variable container, in addition to the type and value of the variable, includes two bytes of extra information. The first one is "Is_ref", which is a bool value, Used to identify whether this variable is a reference collection (reference set). This byte allows the PHP engine to separate the normal variable from the reference variable. Because PHP enables users to use custom references by using &, there is an internal reference counting mechanism in the Zval variable container. To optimize memory usage. The second extra byte is "RefCount", which represents the number of variables (also known as symbols) that point to the Zval variable container.

When a variable is assigned a constant value, a Zval variable container is generated, as shown in the following example:

  <?php   $a = "new string";      ? >


In the example above, the new variable is a, which is generated in the current scope. and a variable container of type string and a value of "new string" is generated. In the additional two bytes of information, "Is_ref" is set to False by default because there are no custom references generated. " RefCount "is set to 1 because there is only one variable that uses this variable container. Call Xdebug to see the contents of the variable:

  <?php   $a = "new string";      Xdebug_debug_zval (' a ');   ? >


The above code will output:

  A: (refcount=1, is_ref=0) = ' new String '


Add a reference count to variable a

  <?php   $a = "new string";      $b = $a;   Xdebug_debug_zval (' a ');   ? >


The above code will output:

  A: (refcount=2, is_ref=0) = ' new String '


At this point, the number of references is 2 because the same variable container is associated with the variable A and variable B. When not necessary, PHP does not replicate the generated variable container. The variable container is destroyed when "RefCount" becomes 0 o'clock. When any variable that is associated to a variable leaves its scope (for example, the function execution ends), or call the unset () function on the variable, "RefCount" will be reduced by 1, the following example can be explained:

  <?php   $a = "new string";   $b = $c = $a;   Xdebug_debug_zval (' a ');   Unset ($b, $c);   Xdebug_debug_zval (' a ');   ? >


The above code will output:

  A: (refcount=3, is_ref=0) = ' new String ' A: (Refcount=1, is_ref=0) = ' new String '


If we now execute unset ($a), $ contains the type and value of this container will be removed from memory

Composite type (compound types)

When considering composite types such as array and object, things can be a little more complicated. Unlike scalar-type values, The array and object type variables have their members or attributes present in their own symbol table. This means that the following example will generate three Zval variable containers

  <?php   $a = array (' meaning ' = = ' life ', ' number ' =);      Xdebug_debug_zval (' a ');   ? >


The above code output:

  A: (Refcount=1, is_ref=0) =array (' meaning ' = (refcount=1, is_ref=0) = ' life ', ' number ' = = (Refcount=1, is_ref=0) =42 )


These three zval variable containers are: A,meaning,number. The rules for adding and reducing refcount are the same as the one mentioned above


Special case, when adding the array itself as an array element:

  <?php   $a = array (' one ');      $a [] = & $a;      Xdebug_debug_zval (' a ');   ? >


The result of the above code output:

  A: (refcount=2, is_ref=1) =array (0 = (refcount=1, is_ref=0) = ' one ', 1 = (refcount=2, is_ref=1) = ...)


You can see that the array A and the elements themselves a[1] The variable container refcount to 2

When the unset function is called by an array $ A, the $a refcount becomes 1 and a memory leak occurs

problems cleaning up variable containers Although no longer has any symbols in a scope pointing to the structure (that is, the variable container), the array element "1" still points to the array itself, so the container cannot be eliminated. Because there is no other symbol pointing to it, the user has no way to clear the structure, The result is a memory leak. Fortunately, PHP will clear this data structure at the end of the request, but before PHP clears, it will consume a lot of memory space


Recovery Cycle 5.3.0PHP uses a new synchronization cycle recovery algorithm to handle the above mentioned memory leak problem

First, let's start by setting up some basic rules:
If a reference count increases, it will continue to be used, of course, no longer in the garbage. If the reference technology is reduced to zero, the variable container is cleared (free). That is, the garbage cycle (grabage cycle) occurs only when the reference count is reduced to a value other than 0. Second, in a garbage cycle , by checking whether the reference count is minus 1, and checking which variable containers have a reference number of zero, to find out which part is garbage

To avoid having to check the garbage cycles that all reference counts may be reduced, the algorithm places all possible roots (possible roots are zval variable containers) in the root buffer (in the purple flag), which ensures that each possible garbage root ( Possible garbage Root) appears only once in the buffer. Garbage collection is performed on all the different variable containers inside the buffer only when the root buffer is full.

Summary : The above is the entire content of this article, I hope to be able to help you learn.

Related recommendations:

PHP Implementation method based on SimpleXML to generate and parse XML

PHP Implementation method based on XmlWriter operation XML

PHP namespaces, traits and builder case studies

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.