In-depth analysis of PHP garbage collection mechanism to deal with memory leaks _php tips

Source: Internet
Author: User

Last time we talked about RefCount and Is_ref, here's a memory leak.

Copy Code code as follows:

$a = Array (1, 2, & $a);
unset ($a);

in the old version of PHP, there will be a memory leak, the analysis is as follows:

To perform the first line, you can know that $a and $a[2] point to the Zval refcount=2,is_ref=1

Then execute the second line, $a will be removed from the symbol table, pointing to the Zval refcount--, Refcount=1, because refcount!=0, so zval will not be used as garbage collection, but at this time we have lost $a[2] Point to the entrance to this zval, so this zval into a piece of memory garbage

The same can happen in a class internal reference, such as

Copy Code code as follows:

$a = new Man ();
$a->self = & $a;
unset ($a);

So how to solve this problem, the new GC mechanism uses an algorithm to solve this problem

PHP has a root buffer for storing Zval node information, when the root buffer is full or the GC function is manually invoked, the GC algorithm starts

For a zval of an array or class type, when the garbage collection mechanism starts, the algorithm iterates through the zval of the element/member within the Zval array/class and RefCount minus 1, if the zval is reduced to 0 after the traversal is completed, It means that this zval is a memory garbage that he will be destroyed, see the example below

Copy Code code as follows:

$a = Array (1, 2, & $a, & $a);
unset ($a);

Easy to know $a pointing zval, assuming Z1 refcount=3,is_ref=1

When unset ($a) executes, the $a has been deleted from the symbol table, and we have lost access to the Z1, at this time Z1 refcount=2,is_ref=1

When the GC is started, the Zval refcount of the Z1 array element is traversed to reduce 1, traversing to a[2] Z1 refcount--a[3, z1 refcount--when z1 = 0 to mark RefCount as memory garbage. Algorithm to reclaim it after

The

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.