Detailed explanation of PHP garbage collection mechanism_PHP tutorial

WBOY
Release: 2016-07-13 17:16:07
Original
963 people have browsed it

PHP can automatically manage memory and clear objects that are no longer needed. PHP uses a simple garbage collection mechanism called reference counting. Each object contains a reference counter, and each reference connected to the object increases the counter by one. When reference leaves the living space or is set to NULL, the counter is decremented by 1. When the reference counter of an object reaches zero, PHP knows that you no longer need to use this object and releases the memory space it occupies

The garbage collection mechanism used before PHP 5.3 was a simple "reference counting", that is Each memory object is assigned a counter. When the memory object is referenced by a variable, the counter + 1; when the variable reference is removed, the counter - 1; when the counter = 0, it indicates that the memory object is not used, and the memory object is Destroyed and garbage collection completed.

There is a problem with "reference counting", that is, when two or more objects refer to each other to form a ring, the counter of the memory object will not be reduced to 0; at this time, this group of memory objects is no longer useful, but Cannot be recycled, causing memory leaks;

Starting from php5.3, a new garbage collection mechanism is used. Based on reference counting, a complex algorithm is implemented to detect the existence of reference rings in memory objects to avoid memory leaks.

PHP variables exist in a variable container called "zval". The "zval" variable container includes the type and value of the variable, and also includes two additional bytes of information, namely "is_ref" indicating whether the variable is a reference. "refcount" points to the number of variables in this zval variable container.

If you have xdebug installed, you can use xdebug_debug_zval() to display "zval" information. As follows:

$str = "www.bKjia.c0m";
xdebug_debug_zval('str');


Result:

str:

(refcount=1, is_ref=0),

string 'phpddt.com' (length=10)

Only when the variable container is destroyed when "refcount" becomes 0. When you unset() a variable, the refcount in the desired "zval" will be reduced by 1. Let's talk about what we encountered a few days ago. unset reference problem:

The code is as follows Copy code
代码如下 复制代码

$a = "aaa";
$b = & $a;
unset($a);
//echo $b; //这里依然会输出aaa,用xdebug_debug_zval打印你就知道为什么了
xdebug_debug_zval("b");

结果:

b:

(refcount=1, is_ref=0),string 'aaa' (length=3)

$a = "aaa";

$b = & $a;

unset($a);

//echo $b; //aaa will still be output here, print it with xdebug_debug_zval and you will know why
代码如下 复制代码


$arr = array( 'a' => 'aaa', 'b' => "bbb" );
 xdebug_debug_zval( 'arr' );
 $arr['aaa'] = $arr['a'];
 xdebug_debug_zval( 'arr' );
?>


结果:

arr:

(refcount=1, is_ref=0),

array

  'a' => (refcount=1, is_ref=0),string 'aaa' (length=3)

  'b' => (refcount=1, is_ref=0),string 'bbb' (length=3)

arr:

(refcount=1, is_ref=0),

array

  'a' => (refcount=2, is_ref=0),string 'aaa' (length=3)

  'b' => (refcount=1, is_ref=0),string 'bbb' (length=3)

  'aaa' => (refcount=2, is_ref=0),string 'aaa' (length=3)

xdebug_debug_zval("b"); Result: b: (refcount=1, is_ref=0),string 'aaa' (length=3) Continuing to talk about the reference counter issue, the situation is different for array and object types:
The code is as follows Copy code
<🎜> $arr = array( 'a' => 'aaa', 'b' => "bbb" ); xdebug_debug_zval( 'arr' ); $arr['aaa'] = $arr['a']; xdebug_debug_zval( 'arr' ); ?> Result: arr: (refcount=1, is_ref=0), array 'a' => (refcount=1, is_ref=0),string 'aaa' (length=3) 'b' => (refcount=1, is_ref=0),string 'bbb' (length=3) arr: (refcount=1, is_ref=0), array 'a' => (refcount=2, is_ref=0),string 'aaa' (length=3) 'b' => (refcount=1, is_ref=0),string 'bbb' (length=3) 'aaa' => (refcount=2, is_ref=0),string 'aaa' (length=3)


You can see that the original array elements and the newly added array elements are associated with the same zval variable container of "refcount" 2. Here I am just playing the role of sparking ideas.

Above we simply used unset, null, mysql_close, __destruct, xdebug_debug_zval and then read on


Check whether the memory is leaked

To see if the memory that should be released has not been released, you can simply call the memory_get_usage function to check the memory usage; the memory usage data returned by the memory_get_usage function is said to be not very accurate. You can use the xdebug extension of php to get more accurate Informative memory usage.

The code is as follows
 代码如下 复制代码

class A{
    private $b;
    function __construct(){
        $this->b = new B($this);
    }
    function __destruct(){
        //echo "A destructn";
    }
}

class B{
    private $a;
    function __construct($a){
        $this->a = $a;
    }
    function __destruct(){
        //echo "B descturctn";
    }
}

for($i=0;;$i++){
    $a = new A();
    if($i%1000 == 0){
        echo memory_get_usage()."n";
    }

}

}

Copy code

class A{

private $b;

Function __construct(){

           $this->b = new B($this);

}

Function __destruct(){

            //echo "A destructn";

}

}

class B{

private $a;

Function __construct($a){

           $this->a = $a;
}

Function __destruct(){

            //echo "B descturctn";

}

}

for($i=0;;$i++){

$a = new A();

If($i%1000 == 0){

echo memory_get_usage()."n";

}

}

}

The above constructs an example that will generate a circular reference; every time an instance a of the A object is created, a creates an instance b of the B object, and at the same time lets b refer to a; in this way, each A object will always be A B reference, and each B object is also referenced by an object A; this is how a reference cycle is generated.

When you execute this code in the php5.2 environment, you will find that the memory usage is increasing monotonically, and there is no "A/B destructurt" information output after the destructors of A and B are executed; until the memory is exhausted, Output "PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 40 bytes)".

When executing this code in the php5.3 environment, it is found that the memory usage jumps up and down, but never exceeds a limit; the program will also output a large number of "A/B desctruct", which indicates that the destructor function was called.

My colleague’s program has this kind of reference loop, and his script is actually executed under php5.2.3. In the simple_html_dom tool, there are two classes, namely simple_html_dom and simple_html_dom_node. The former has an array member variable nodes, and each element in the array is a simple_html_dom_node object; and each simple_html_dom_node object has a member variable dom, which is The value is the previous simple_html_dom object - thus forming a beautiful reference loop, leading to a memory leak. The solution is also very simple, that is, when the simple_html_dom object is finished using, actively call its clear function and clear its member variable nodes, the loop will be broken, and memory leaks will not occur.
3. Others: 1) Timing of garbage collection In Php, when the reference count is 0, the memory is released immediately; that is to say, if there is no circular reference to the variable, the memory is released immediately after leaving the scope of the variable. Circular reference detection is triggered when certain conditions are met, so in the above example, you will see large fluctuations in the memory used; you can also actively perform circular reference detection through the gc_collect_cycles function. 2) The impact of & symbol Explicitly referencing a variable will increase the reference count of the memory: $a = "something"; $b = &$a; At this time unset($a), but there is still a reference to $b pointing to the memory area, and the memory will not be released. 3) The impact of unset function Unset just disconnects a variable from a memory area and reduces the reference count of the memory area by -1; in the above example, inside the loop body, $a=new A(); unset($a) ;Does not reduce $a’s reference count to zero; 4) = impact of null operation; $a = null directly nulls the data structure pointed to by $a and returns its reference count to 0. 5) Impact of the end of script execution When the script execution ends, all memory used in the script will be released, regardless of whether there is a reference cycle.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/628717.htmlTechArticlePHP can automatically manage memory and clear objects that are no longer needed. PHP uses a simple garbage collection mechanism called reference counting. Each object is within...
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!