Understanding the garbage collection mechanism in PHP _php skills

Source: Internet
Author: User
Tags garbage collection php language memory usage scalar

Basic GC Concepts for PHP
The PHP language, like any other language, has a garbage collection mechanism. So today we are going to explain the content of the PHP garbage collection mechanism related issues. Hope to help you. PHP strtotime Application Experience PHP memory_get_usage () Manage memory PHP unset global variable application problem detailed PHP unset () function destroy variable teach you to quickly implement PHP full station permissions to verify a, PHP garbage collection mechanism ( Garbage Collector (GC) in PHP, when no variable points to this object, the object becomes garbage. PHP will destroy it in memory; this is the GC garbage disposal mechanism in 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 typically runs with each session. The purpose of the GC is to automatically destroy the deleted files after they expire. Ii. __destruct/unset __destruct () destructor, which is executed when the garbage object is reclaimed.
Unset destroys a variable that points to an object, not the object. Third, session and the PHP garbage collection mechanism because of the working mechanism of PHP, it does not have a daemon thread regularly 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_divisor values to determine whether to enable a GC, by default, Session.gc_probability=1, Session.gc_divisor = 100 means there are 1% The possibility of starting a GC (that is, only one GC in 100 requests will be started with one of 100 requests). The job of the PHP garbage collection mechanism is to scan all session information, subtract the time of the session last modified with the current time, and compare it with the Session.gc_maxlifetime parameter if the lifetime exceeds Gc_maxlifetime (default 24 minutes ), the session is deleted.
However, if your Web server has multiple sites, multiple sites, GC processing session may have unexpected results, because the GC at work, does not distinguish between different site sessions. So how to solve this time?
1. Modify the Session.save_path, or use Session_save_path () to save each session of the site to a dedicated directory,
2. To provide the starting rate of GC, naturally, the PHP garbage collection mechanism of the startup rate increased, the system performance will be reduced, not recommended.
3. In the code to determine the current session life time, using Session_destroy () Delete.


basic knowledge of reference counting
each PHP variable exists in a variable container called "Zval". A Zval variable container that includes two bytes of extra information in addition to the type and value of the variable. The first is "Is_ref", a bool value that identifies whether the variable belongs to a reference collection ( Reference set). Through this byte, the PHP engine can separate the normal and reference variables. Because PHP allows users to use custom references by using &, the Zval variable container also has an internal reference counting mechanism to optimize memory usage. The second extra byte is " RefCount ", which represents the number of variables (also known as symbol symbols) that point to this 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, is generated in the current scope. and a variable container of type string and value "new string" is generated. In the extra two bytes of information, "Is_ref" is set to False by default because there are no custom reference builds. " RefCount "is set to 1, because there is only one variable using this variable container." Call Xdebug to view the variable contents:

  <?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 variable A and variable B. PHP does not copy the generated variable container when it is not necessary. The variable container is destroyed when the "RefCount" becomes 0 o'clock. When any variable that is associated with an easy variable leaves its scope (for example, the end of the function execution), or call the unset () function on a variable, "refcount" will be reduced by 1, as the following example illustrates:

  <?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 execute unset ($a) Now, $ contains the type and value of this container will be removed from memory

Compound type (compound types)

When considering composite types like array and object, things are slightly more complex. Unlike the value of a scalar (scalar) type, Variables of array and object type have their members or attributes in their own symbol table. This means that the following example generates three Zval variable containers

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


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 increasing and reducing refcount are the same as those mentioned above


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

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


The results 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 group itself element A[1] points to a variable container refcount 2

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

To clean up variable container issues
Although no longer has any symbol in a scope that points to this struct (that is, the variable container), because the array element "1" still points to the array itself, the container cannot be eliminated. Because there is no other symbol pointing to it, the user has no way to clear the structure, resulting in a memory leak. Thankfully, PHP will clear the data structure at the end of the request, but it will take a lot of memory before the PHP clears.


Recycle cycle
5.3.0PHP uses a new synchronous cycle recovery algorithm to deal with the memory leak problem mentioned above

First, we'll start with some basic rules:
If a reference count is added, it will continue to be used, of course it's no longer rubbish. If the referral technique is reduced to zero, the variable container is cleared (free). That is, the garbage cycle (Grabage cycle) is generated only when the reference count is reduced to a value other than 0. Second, in a garbage cycle , check to see if the reference count is minus 1, and check which variable containers have a reference number of zero, to find out which part is garbage

To avoid having to check garbage cycles that all reference counts may be reduced, this algorithm puts all possible roots (possible roots are zval variable containers) in the root buffer (in the case of a purple flag), which ensures that each possible garbage root ( possible garbage root) occurs only once in the buffer. Garbage collection is performed on all different variable containers within the buffer only when the root buffer is full.

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.