Know What Triggers GC
As you now know, GC must control both the object allocation in the heap space and the object memory allocation outside the Ruby heap. Consequently, two events will trigger GC:
There are not enough free slots in the heap space.
The current memory allocation (malloc) limit has been exceeded.
So any object creation or memory allocation can invoke GC. Let’s see when that happens, and then talk about how we can reduce the number of GC runs.
GC Triggered by Heap Usage
When Ruby runs out of slots, it executes GC to free up some memory. If GC can’t free enough slots, Ruby increases the heap space as described earlier.
Ruby defines enough slots as either 20% of all allocated slots, or GC_HEAP_FREE_SLOTS (FREE_MIN in Ruby 2.0 ...