Home > Article > Backend Development > Detailed explanation of PHP memory release and garbage collection
This time I will bring you a detailed explanation of the use of PHP memory release and garbage collection. What are the precautions for PHP memory release and garbage collection? The following is a practical case, let's take a look.
QuoteAssignment
$a = 'apple'; $b = &$a;In the above code, I assign a
string to the variablea, and then assign the reference of a to variable b. Obviously, the memory pointing at this time should be like this:
$a -> 'apple' <- $ba and b point to the same memory area. We get string(5) "apple" string(5 through var_dump($a, $b) ) "apple" , which is what we expected. Suppose I want to release the string 'apple' from memory. This is what I did:
unset($a);But by printing the information of the $a $b two variables again, I got this result: Notice: Undefined variable: a and string(5) "apple" . Strangely, $a and $b both point to a memory area, and $a is clearly released. Why is $b still 'apple'. Actually, unset() destroys a variable pointer and does not release the string stored in that memory area. Therefore, after the operation is completed, the memory pointer just becomes like this :
'apple' <- $bImportant points to remember: unset() does not release the memory pointed to by the variable, but only destroys the variable pointer. At the same time, the reference count of that piece of memory is decremented by 1. When the reference count is 0, that is to say, when that piece of memory is not referenced by any variable, PHP's garbage collection will be triggered.
Direct recycling
So what can be done to really release the memory occupied by 'apple'? Using the above method, we can unset($a) and then unset($b) to destroy all references in the memory area. When the reference count is reduced to 0, it will naturally be recycled by PHP. Of course, there is a more direct method:$a = null;Direct assignment to null will empty the memory area pointed to by $a, reset the reference count to zero, and the memory will be released.
End of script execution
php is a scripting language. When the script execution ends, all the memory used in the script will be released. I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! Recommended reading:Detailed explanation of the use of PHP template method pattern
thinkPHP framework automatic filling principle and usage detailed explanation
The above is the detailed content of Detailed explanation of PHP memory release and garbage collection. For more information, please follow other related articles on the PHP Chinese website!