Garbage Collection Flashcards
A PHP variable is stored in a container called…
…zval
What does a zval container contain?
- the variable’s type
- the variable’s value
- is_ref: a boolean value indicating whether or not the variable is part of a “reference set”
- refcount: an internal reference counting mechanism to optimize memory usage
What does refcount contain?
It contains how many variable names (also called “symbols”) point to this one zval container. All symbols are stored in a symbol table, of which there is one per scope. There is a scope for the main script, as well as one for every function or method.
When is a zval container created?
When a new variable is created with a constant value.
What is the is_ref bit set to by default?
FALSE. Note that if refcount is 1, is_ref is always FALSE.
How can you display zval information
If you have Xdebug installed, you can display it with xdebug_debug_zval.
When are variable containers destroyed?
When the refcount reaches 0.
When does the refcount get decreased by 1?
When any symbol linked to the variable container leaves the scope (e.g. when the function ends), or when unset() is called on a symbol.
How many zval containers are created from a 2-element array?
- One for the array, and one for each element in the array.
What is the zend.enable_gc php.ini setting?
It enables or disables the circular reference garbage collector. It’s enabled by default.
How can the garbage collecting mechanism be turned on and off?
By calling gc_enable() or gc_disable().
What does gc_collect_cycles() do?
It forces the collection of cycles even if the possible root buffer is not full yet. It returns how many cycles were collected by the algorithm.
Why is it wise to call gc_collect_cycles() just before you call gc_disable()?
To free up the memory that could be lost through possible roots that are already recorded in the root buffer. This then leaves an empty buffer so that there is more space for storing possible roots while the cycle collecting mechanism is turned off.
What is a memory leak?
It’s when memory that is no longer needed is not released.
What are the two performance considerations of garbage collection?
- Reduced memory usage.
2. Run-time delay when the garbage collection mechanism performs its memory cleanups.