Understand Why GC in Ruby 2.1 and 2.2 Is So Much Faster

In this book we repeatedly observed that new Ruby versions consistently perform better because the GC is faster. But why is it faster?

The first reason it’s faster is that less GC is needed. We have just seen that with our memory allocation example. The second reason is that each individual GC run can take less time.

Ruby implements GC using a simple two-phase mark and sweep (M&S) algorithm. In the mark phase it finds all living objects on the Ruby heap and marks them as live. In the sweep phase it collects unmarked objects.

Naturally, GC can’t allow you to allocate new objects while it marks. So your program pauses for the duration of GC.

Ruby 2.1 with RGenGC reduces the number of pauses, and Ruby with RIncGC optimizes the pause time.

RGenGC takes advantage of the fact that most objects die young. So most of the time GC needs to collect only the objects from the new generation. This is called Minor GC. Major GC happens when objects from both new and old generations are collected. Minor GC is very fast because it has fewer objects to mark and sweep, and most of the GC runs are minor—hence the optimization.

RIncGC performs the mark phase incrementally. It does not decrease the pause time, but rather distributes it. This way your program has a chance to finish its job in between incremental mark phases. Note that the overall GC time is not changed. So long-running code will see no difference between RGenGC and RIncGC. Refer to the Koichi Sasada’s blog post[41] for a good visualization of this process.

Although we barely sketched Ruby GC internals, you should already understand why Ruby 2.1 and 2.2 perform so much better. If you are interested in GC architecture, there’s no better description than Sasada’s blog post or the recordings of his talks that I mentioned earlier.

While Ruby became faster out of the box in versions 2.1 and 2.2, it might still not perform optimally in your case. Depending on your object and memory allocation patterns, it might make sense to tweak Ruby GC for performance. Let’s see how.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.70.185