Analysis: PHP garbage collection mechanism

WBOY
Release: 2016-07-25 08:56:35
Original
962 people have browsed it
  1. $a=array(1,4,5);
  2. $b=$a;//The array is not copied
  3. $a[1]=10;//The array is copied , and modified the value
  4. print_r($a);
  5. print_r($b);
  6. ?>
Copy the code

After running, the values ​​of $a and $b are different. $a is 1,10,5 $b is 1,4,5 This is somewhat similar to the assignment of value types in C#. To make $a and $b always have the same reference, the code is written as:

  1. $b=&$a;
Copy code

A term used in PHP that goes with Copy-on-write technology is called reference count. Each variable in PHP consists of two parts, one is the variable name, and the other is the value of the variable. They are stored in a structure called a symbol table. This symbol table is an array, which maps the variable name and value. location in memory. Each value in the symbol table has a so-called reference count, which records how many ways to obtain this value, that is, how many variable names point to this value.

In the above code, when $a is initialized and $b=$a, the array has a reference count of 2 (if you check the reference count through the C API method, this value is actually 3, but from From a user perspective, it is better to explain it as 2). The value in this memory can be obtained in two ways, through $a and $b. Then when the value of $a[1] changes, PHP creates a new memory space for $a, that is, two arrays appear. . Both arrays have a reference count of 1.

When a variable goes out of scope, such as a local variable in a function, and the variable becomes invalid after the function finishes running, then the reference count of the value pointed to by the variable will be reduced by 1. Similarly, if a variable points to a new memory address, the reference count at the value of the old address will also be decremented by 1.

When the reference count of a memory space reaches 0, it will be released by PHP.



source:php.cn
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!