In previous post, I described which tools I use for debugging Rails (Ruby) applications.
In this post I will show you how to debug your Garbage Collector.
Why should I debug my GC?
First, you should understand how ruby allocates memory for new objects.
What happened inside your OS, each time you write
book = Book.new?
RVM defines Process Heap for each Ruby process. Than, it creates first Ruby Heap. Each Ruby Heap contains allocated objects. There is a “Free List” array inside the heap.
While new object allocated, the RVM looks for an empty place in “Free List” and allocates it for a newly creted one. If the “Free List” is empty (all slots are allocated), RVM calls to Garbage Collector (GC).
The Garbage Collector finds non-reachable objects and remove them. If “Free List” is still empty, another Heap allocated.
Conclusion: The more objects we have, the longer GC process. And it’s a cause for slow application.
How should I debug my GC?
I suggest to use pry-debugger.
There are several tools we can use while debugging:
- ObjectSpace class
- Heap dump (via GC patch)
But to get it all functionality you need to use patched version of Ruby.
To enable heap dump support, pass the -enable-gcdebug option to the rvm install command:
- ObjectSpace.count_objects - returns a hash of counts objects of each type
- Visualizing memory leaks in Ruby
An example of method I used to get a better output:
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8
Other interesting solutions to check:
- gdb7 hooks for MRI
- Why You Should Be Excited About Garbage Collection in Ruby 2.0
- Trace for Ruby
- GoRuCo 2010 - Aman Gupta - memprof: the ruby level memory profiler - A little bit outdated but very interesting
Note: the memprof works only with Ruby 1.8.x