Using the PHP Function GC_Collect_Cycles
PHP's Garbage Collection (GC) mechanism helps reduce memory usage by cleaning circular references. But it can also cause problems if not used properly and can lead to unnecessarily long running scripts that consume lots of CPU time. So GC is one of the most important parts of PHP's memory management. Fortunately, you can have a lot of control over when it runs by using the gc_collect_cycles function.
Normally when a variable ends its scope in your code, it is garbage collected automatically by the GC routine. However, if you manually end the scope of a variable early by unset() or a similar method you can prevent that from happening and save some memory.
The GC works by analyzing a graph structure that represents the entire set of variables in your code. Each node in the graph represents an actual zval (arrays, objects or strings) and the edges represent connections/references between them. The GC algorithm uses this graph marking to find possible cyclic references. If it finds any such possible cycles it starts the garbage collection mechanism. This is done by analyzing the root buffer which has a fixed size of 10,000 possible roots (this can be changed by changing the GC_ROOT_BUFFER_MAX_ENTRIES value in the zend/zend_gc.c file and recompiling PHP).
This means that if you call gc_collect_cycles() you're forcing the GC to start a cycle-finding analysis and potentially free up some memory. But you might want to do this only in cases where you know that a significant memory utilization is about to occur, e.g. when you're measuring the memory consumption of a certain block of your code with memory_get_usage().