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
gc/default/default.c
View on GitHub ↗
static VALUE
gc_compact(VALUE self)
{
rb_objspace_t *objspace = rb_gc_get_objspace();
int full_marking_p = gc_config_full_mark_val;
gc_config_full_mark_set(TRUE);
/* Run GC with compaction enabled */
rb_gc_impl_start(rb_gc_get_objspace(), true, true, true, true, true);
gc_config_full_mark_set(full_marking_p);
return gc_compact_stats(self);
}
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)