Rubyは自動的にガベージコレクタ(GC)を介してメモリを管理し、参照されなくなったオブジェクトを回収します。モダンRuby(MRI)は世代別、インクリメンタルなマーク・アンド・スウィープコレクタとコンパクションを使用しています。このメカニズムを理解することは、長時間実行されるアプリケーションのパフォーマンスとメモリ問題の診断に役立ちます。
自動ガベージコレクション
Ruby allocates objects on the heap; the GC reclaims those that are no longer REACHABLE
(referenced). You never free memory manually.
Modern MRI GC characteristics:
✓ Mark-and-sweep — marks reachable objects (from roots), sweeps unreachable ones
✓ Generational (since Ruby 2.1) — new objects collected often, old ones rarely
(based on "most objects die young")
✓ Incremental — spreads GC work to reduce pause times
✓ Compacting (GC.compact, Ruby 2.7+) — reduces memory fragmentation
