Use a "reference count" method for recycling. Simply understood, there is a counter in each allocated memory area that records how many variable pointers point to this piece of memory. When the number of pointers to this slice of memory is 0, the memory area of the slice can be reclaimed.
The reference count count is simple and powerful, but there is a fatal flaw, the ring reference. Consider the following code:
PHP code
$a = array ();
$a [] = & $a;
unset ($a);
The variable $ A refers to itself, forming a ring. The $a was unset, but because of a circular reference, a reference count of $ A before a $ A was 1, so the memory area is not reclaimed by the garbage collection mechanism.
The PHP5.3 is optimized for this major flaw. Although the basis is still reference counting, some improvements have been made to control the memory leaks caused by ring references to a certain scale. Of course, this is not to say you can abuse the memory casually, write code still need to be careful!
Other Highlights:
The 1.PHP script finishes running and all the memory space requested by the script is freed, regardless of whether there is a ring reference. Therefore, the issue of ring-referenced memory leaks generally only affects long-running program scripts.
2. The garbage collection mechanism needs to meet certain conditions before it can be executed. Therefore, after unset, the system does not necessarily recycle rubbish immediately.
The role of 3.unset.
"Unset just disconnects a variable into a chunk of memory, and then counts the reference count of that memory area at 1". That is, if more than one variable points to the same memory area, or if there is a ring reference, then unset does not release the memory area. Disconnecting also indicates that unset does not directly delete the memory area, but only changes its reference count.
4. $xx the role of =null.
"$a = null is to empty the data structure pointed to by $ A directly, and its reference count to 0". Based on my understanding of this definition, the =null operation can immediately free up memory space! As a result, many PHP tips have been very tedious to say to us, first set the variable to null, and then unset. After understanding its deep-seated principles, I thoroughly understood the reason for doing so! =null is the kingly way!
PHP garbage Collection Mechanism understanding