Ruby's garbage collector
In Ruby, almost everything you do requires memory.
The job of the Ruby garbage collector is to manage memory and eventually release objects that are no longer in use. But this would sacrifice a bit of performance, and it would need to suspend people's programs when it worked.
How does it work?
It uses a process called Mark-erase (Mark and sweep). First, the object graph is traversed, and the objects that can be accessed are marked as surviving. Then, any objects that are not marked in the first stage are considered garbage and clear, and then released back to Ruby or the operating system. And it is expensive to traverse the entire object graph and mark accessible objects.
The ruby2.1 is optimized for performance with a new generational garbage collector. The objects are divided into two categories, the younger generation and the old generation. There is a premise: most objects will not have a very long lifetime. For long-lived objects, such as constants, the garbage collector can refine the tags and automatically mark these old objects as accessible without having to traverse the entire object graph.
If the younger generation objects survive in the first stage of the tag, then Ruby's generational garbage collector promotes them to older generations. It is also said that after the last garbage collection, they are still accessible.
The marking stage can be divided into two modes: the primary marker stage and the minor mark stage. In the primary tagging phase, all objects (no new or old) are marked, so the overhead is high. In the secondary tagging phase, only the younger generation objects are considered, and the old objects are automatically tagged without checking whether they can be accessed. This means that older generations of objects will only be purged after the primary tagging phase. The garbage collector tends to use secondary tags.
The purge phase of the garbage collector is also divided into two modes: Instant mode and lazy mode. In instant mode, the garbage collector clears all unmarked objects. This pattern is expensive if there are many objects that need to be freed. Lazy mode tries to free as few objects as possible when Ruby creates a new object, and it tries to trigger a lazy cleanup phase to free up some space.
Ruby's request for memory from the operating system's free storage can be expensive, usually because it allocates more redundant memory when allocated, and maintains a pool of memory that only requests additional memory from the operating system after the memory pool is allocated.
Ruby's memory management