A Brief Talk on the Garbage Collection Mechanism of PHP

  • 2021-09-12 00:44:48
  • OfStack

1. Each variable is stored in a container called zval when defined, which contains the type and value of quantity, and also contains two additional information: refcount (understood as the number of several variables) and is_ref (understood as whether it is a reference variable). When a variable is referenced once, refcount will be +1, and when you are under unset1, this value will be reduced by 1 until it is 0 and will be deleted from memory

2. When defining a variable, it does not enlarge the predetermined value every time, because PHP will pre-occupy 1 space in memory, which will be allocated to you when you declare the variable, but when you exceed this pre-occupied space, it will increase the space, but when you delete the variable, this space capacity will not disappear immediately

3. The reference of variable will not increase the memory occupation alone, it will point to zval structure, only refcount+1

4. To put it simply, the variables of PHP depend on an internal implementation of symbol_table symbol table, and the basic implementation of symbol table is HashTable, which is identical to the basic implementation of PHP array. Because of the existence of symbol table, we can use global to mark global variables, and use functions such as compact to pull variables directly from the current symbol table.

When talking about whether unset ($a) will free up space immediately, the answer is no. unset supports deleting the element named a from the symbol table (just marking that this space is available again, not freeing up space).

Let's talk about the case where $key is updated repeatedly in the loop, because the variables are updated with the same name, so they are the same element in the symbol table, and the same position will be updated when updating, and the values of the previous elements will be overwritten immediately.

Besides, if you state that the new variable memory will increase, the answer is not sure. This is due to the characteristics of symbol table based on HashTable. HashTable does not apply for memory of one element when adding one element, but applies for memory of multiple elements at a time (only these location marks are not used), and when HashTable is full, it applies for memory of new multiple elements. That is to say, When we declare or assign a variable, If it is not in the symbol table, PHP will add it to the symbol table, and if the symbol table is not full at this time, it will use the memory that has been applied but not used in the symbol table. If the symbol table is just full, it will apply for new memory to store, and the new memory is not only as small as the memory required by this variable


Related articles: