Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
ObjectSpace.memsize_of
static VALUE
memsize_of_m(VALUE self, VALUE obj)
{
return SIZET2NUM(rb_obj_memsize_of(obj));
}
Returns the amount of memory in bytes consumed by obj.
The returned size includes the slot that obj occupies plus any memory that obj allocates outside of that slot, such as the storage backing a large String, Array, or Hash:
require 'objspace' ObjectSpace.memsize_of("small") # => 40 ObjectSpace.memsize_of("a" * 1000) # => 1041 ObjectSpace.memsize_of([1, 2, 3]) # => 40 ObjectSpace.memsize_of(Array.new(100)) # => 840
Special constants such as true, false, nil, small integers, and some symbols do not occupy a slot, so their size is reported as 0:
ObjectSpace.memsize_of(true) # => 0 ObjectSpace.memsize_of(42) # => 0
The returned size is only a hint and may be an underestimate, since it does not account for all of the memory that obj references. In particular, the size of a T_DATA object (an object implemented in C, such as one defined by a C extension) may not be reported correctly.
This method is only expected to work with CRuby.