# Demystifying the Ruby GC

DevFeed: [Demystifying the Ruby GC](<https://devfeed.tech/articles/demystifying-the-ruby-gc-41331.md>)

Original publisher: [Read original article](<https://samsaffron.com/archive/2013/11/22/demystifying-the-ruby-gc>)

Author: Sam Saffron

Published: 2013-11-22T05:15:36Z

Content type: tutorial

Language: en

Sources: [Sam Saffron](<https://devfeed.tech/sources/sam-saffron.md>)

Topics: [Ruby](<https://devfeed.tech/topics/ruby.md>), [Algorithms, Complexity](<https://devfeed.tech/topics/algorithms-complexity.md>), [Programming](<https://devfeed.tech/topics/programming.md>)

Tags: [algorithms](<https://devfeed.tech/tags/algorithms.md>), [gc](<https://devfeed.tech/tags/gc.md>), [ruby](<https://devfeed.tech/tags/ruby.md>)

## AI overview

An explanation of the Ruby garbage collector in Ruby MRI 2.0, covering lazy sweeping in Ruby 1.9.3, bitmap marking in Ruby 2.0, heap and RVALUE memory organization, and selected GC.stat metrics.

## Source excerpt

This article is about the Ruby GC. In particular it is about the GC present in Ruby MRI 2.0. The Ruby GC has been through quite a few iterations, in 1.9.3 we were introduced to the lazy sweeping algorithm and in 2.0 we were introduced to bitmap marking. Ruby 2.1 is going to introduce many more concepts and is out-of-scope for this post. fccfe3a2c3809d58.jpg517x279 17.7 KB Heaps of heaps MRI (Matz's ruby interpreter) stores objects aka. RVALUEs in heaps, each heap is approx 16KB. RVALUE structs consume different amounts of memory depending on the machine architecture. On x64 machines they consume 40 bytes, on x32 machines they consume 20 to 24 bytes depending on the sub-architecture (some optimizations shave off a few extra bytes on say, cygwin using magic pragmas). An RVALUE is a magical c struct that is a union of various "low level" c representations of Ruby objects. For example, in MRI, an RVALUE can be accessed as a RRegexp or a RString or an RObject and so on. I strongly recommend the excellent Ruby Under a Microscope to get a handle of this, GC algorithms and MRI in general. da95e58aa975dafa.png227x300 15.3 KB Given this, in each heap on an x64 machine we are able to store about 409 Ruby objects give or take a few for heap alignment and headers. [1] pry(main)> require 'objspace' => true [2] pry(main)> ObjectSpace.count_objects[:TOTAL] / GC.stat[:heap_used] => 406 A typical Rails application (like say Discourse) will have about 400 thousand objects in 1100 or so heaps (heaps can get fragmented with empty space), we can see this by running: $ RAILS_ENV=production rails c > GC.start > GC.stat => {:count=>102, :heap_used=>1160, :heap_length=>1648, :heap_increment=>488, :heap_live_num=>369669, :heap_free_num=>102447, :heap_final_num=>0, :total_allocated_object=>3365152, :total_freed_object=>2995483} About GC.stat in Ruby 2.0 GC.stat is a goldmine of information, it is the first place you should go to before doing any GC tuning, here is an overview of what they mean