Ruby: garbage collection
This course covers tools for watching and steering Ruby's garbage collector on your own objects. ObjectSpace.each_object counts the live instances of one class, and ObjectSpace.count_objects breaks the heap down by internal type. GC::Profiler records each GC pause with its duration in milliseconds. Two RUBY_GC_* environment variables are tested on Ruby 4.0.1: one has a measurable effect, and the other is deprecated. The course also covers finalizers, including the trap of referencing the object being finalized, and WeakRef, a reference the GC does not count.
What you'll learn
- ✓Counting live objects of a class with ObjectSpace.each_object
- ✓Comparing heap snapshots by type with ObjectSpace.count_objects
- ✓Measuring GC pauses with GC::Profiler
- ✓Testing GC environment variables on your own Ruby version
- ✓Writing finalizers that do not hold a reference to self
- ✓Using WeakRef for references the GC does not count
Counting live objects with ObjectSpace
The lesson "Memory management", in Operating system basics, covered the heap-of-slots model, mark and sweep, generational GC and GC.stat's heap_allocated_pages/heap_live_slots/count fields. It also covered find_each and frozen string literals as memory patterns in Rails. None of that is repeated…
Read the full lesson free →Curriculum
7 lessonsCounting live objects with ObjectSpace
Counting live instances of one class with ObjectSpace.each_object, and why a raw count needs a baseline.
What ObjectSpace.count_objects reveals
Reading the heap by internal type with ObjectSpace.count_objects and comparing snapshots before and after suspect code.
GC::Profiler: watching pauses happen
Recording GC pauses with GC::Profiler, reading its report table and keeping the measurement scoped to suspect code.
Tuning the heap with GC environment variables
Testing RUBY_GC_HEAP_GROWTH_FACTOR, which changes GC run counts, and RUBY_GC_HEAP_INIT_SLOTS, which is deprecated on Ruby 4.0.1.
Finalizers and the object you cannot touch
Scheduling code with ObjectSpace.define_finalizer and why a finalizer that holds self does not run at GC.start.
WeakRef: a reference that doesn't count
Using WeakRef for a reference the GC ignores, what happens when its object is collected, and caching.
Putting it together
A review of the five tools and why the course has no coding challenge.