PHP’s unset() function is used to clear and destroy variables. We can use unset() to destroy unused variables. But sometimes, using unset() cannot destroy the memory occupied by the variable! Let’s look at an example first:
The memory occupied before final output unset() minus unset () takes up memory. If it is a positive number, it means that unset($s) has destroyed $s from the memory (or in other words, the memory usage has decreased after unset()). However, under PHP5 and Windows platforms, I got The result is: -48. Does this mean that unset($s) does not destroy the memory occupied by variable $s? Let’s make the following example again:
This example is almost the same as the above example, the only thing The difference is that $s consists of 256 1's, which is one more 1 than the first example, and the result is: 224. Does this mean that unset($s) has destroyed the memory occupied by $s?
Through the above two examples, we can draw the following conclusions: Conclusion 1. The unset() function can only release the memory space when the variable value occupies more than 256 bytes of memory space.
So as long as the variable value exceeds 256, can using unset free up memory space? Let’s test it with another example:
Refresh the page, we see that the first line has 256 1s, and the second line is -48. It stands to reason that we have destroyed $s, and $p is just a variable that refers to $s, and there should be no content. In addition, the memory usage after unset($s) has increased compared with before unset()! Now let’s do the following example:
Now refresh the page, we see that the output $p has no content, and the difference in memory usage before and after unset() is 224, that is, the memory occupied by the variable has been cleared. $s=null in this example can also be replaced by unset(), as follows:
We use unset() to destroy both $s and $p. At this time, the difference in memory usage is also 224, indicating that this can also release memory. Then, we can get another conclusion: Conclusion 2. The memory will be released only when all variables (such as reference variables) pointing to the variable are destroyed.
I believe that after the examples in this article, everyone should have an understanding of unset(). At the very least, I use unset() to release memory when the variable does not work.
The above introduces PHP unset to destroy variables and release memory, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.