Enabling and Disabling the Garbage Collector in PHP
The garbage collector is a vital piece of memory management in PHP and disabling it can lead to large performance hits in some cases. In this article I will show you how to enable / disable the garbage collector by using the php function gc_disable and also provide some examples of when it is useful and when it isn't.
PHP uses reference counting to help determine when variables are eligible for garbage collection. This means that when a variable is no longer needed it will be discarded at the end of the current request. However, this can result in a significant slowdown if the application is large enough that the references to a lot of variables are removed at once.
To avoid this, PHP has a cycle collector that can help reclaim some of the wasted memory. The cycle collector will run whenever a variable's refcount is decremented but not zero. This adds the object to an array of possible cyclic roots that is kept in memory. When the root buffer reaches 10,000 entries, this will trigger the formal garbage collection to free up some of the space.
This can also be triggered explicitly with the functions gc_enable() and gc_collect_cycles(), but it will still be a slow process for most applications. For this reason, the php function gc_disable() was added in PHP version 5.6.40 and is now available for use in your scripts. You should only call this in places where you know that you don't want the garbage collector to run, as it will still affect your performance.