Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

class method

GC.compact

() -> ::GC::compact_info
GC.compact → hash

This function compacts objects together in Ruby’s heap. It eliminates unused space (or fragmentation) in the heap by moving objects in to that unused space. If there is more than 1 running Ractor, it runs a global GC compaction (all object spaces).

The returned hash contains statistics about the objects that were moved; see GC.latest_compact_info.

This method is only expected to work on CRuby.

To test whether GC compaction is supported, use the idiom:

Example
GC.respond_to?(:compact)
See also .auto_compact= .config .auto_compact .count also in 3.3 · 3.2 · 3.1 · 3.0