Memory, Garbage Collection and Object Lifecycle

CRuby GC: generational (young/old objects), incremental marking, compaction (GC.compact, auto-compaction optional), object allocation in heap pages with variable-width allocation (3.2+). Ruby 3.4 added a modular GC (pluggable GC implementations such as MMTk, experimental).

Tuning (env vars): RUBY_GC_HEAP_GROWTH_FACTOR, RUBY_GC_MALLOC_LIMIT. Use jemalloc (LD_PRELOAD or a jemalloc-built Ruby) to reduce fragmentation in long-running apps. MALLOC_ARENA_MAX=2 for threaded servers on glibc.

Reduce allocations: frozen string literals, symbols, << instead of += for strings, each instead of map when the result is unused, avoiding temporary arrays (sum/count with blocks), lazy.

Find leaks: memory_profiler, derailed_benchmarks, ObjectSpace.trace_object_allocations, heap dumps (ObjectSpace.dump_all) analyzed with heapy/sheap.

GC.stat[:count]; GC.stat[:heap_live_slots]; GC.stat(:total_allocated_objects)
GC.start; GC.compact; GC.disable; GC.enable
ObjectSpace.count_objects
ObjectSpace.memsize_of("x" * 1000)       # require "objspace"
ObjectSpace.define_finalizer(obj, proc { puts "collected" })
WeakRef.new(obj)                         # require "weakref"; also ObjectSpace::WeakMap / WeakKeyMap (3.3)