Ruby 通过自动的垃圾收集器 (GC) 来管理内存,该收集器回收不再被引用的对象。现代 Ruby (MRI) 使用分代、增量 mark-and-sweep 收集器,配合压缩功能。理解它有助于性能优化和诊断长期运行应用中的内存问题。
自动垃圾回收
text
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
