Getting the Most Out of PHP Garbage Collection
Garbage collection, or GC, is one of those things that's both easy to overlook and important to understand in order to write well performing code. The garbage collector is what keeps the memory used by your script from being wasted. This is accomplished by keeping track of how many references are used to an array or variable. Eventually, once there are no more references to the object or variable, it will be garbage collected. This means that the amount of storage that was once occupied by the object or array will now be available for use by another object or variable.
Traditionally, reference count oriented GC mechanisms do not properly address circular references. As of PHP 5.3, however, PHP can now perform cyclic GC by using the synchronized algorithm from the Concurrent Cycle Collection in Reference Counted Systems paper. This is a significant improvement to how PHP handles the issue of cyclic references and it does address an important aspect of long running scripts that are nearly continuously running.
This is a good thing, but it also raises questions about how to best use this feature and how to get the most out of GC. While it is true that GC does have a small overhead due to scanning the memory, this cost is often overblown when it comes to larger memory sizes and the amount of time that it takes for a gc to run is fairly minimal.
With this in mind, it's worth noting that you can alter how GC works by using the gc_enable() and gc_disable() functions as well as modify the size of the root buffer (10,000 entries) that holds all of the roots with a gc_root_buffer_max_entries value from the zend/zend_gc source code. However, it's important to remember that the formal GC runs only once the root table is full and this can take a considerable amount of time in some cases.