Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
ObjectSpace.count_objects_size
static VALUE
count_objects_size(int argc, VALUE *argv, VALUE os)
{
size_t counts[T_MASK+1];
size_t total = 0;
enum ruby_value_type i;
VALUE hash = setup_hash(argc, argv);
for (i = 0; i <= T_MASK; i++) {
counts[i] = 0;
}
each_object_with_flags(cos_i, &counts[0]);
for (i = 0; i <= T_MASK; i++) {
if (counts[i]) {
VALUE type = type2sym(i);
total += counts[i];
rb_hash_aset(hash, type, SIZET2NUM(counts[i]));
}
}
rb_hash_aset(hash, ID2SYM(rb_intern("TOTAL")), SIZET2NUM(total));
return hash;
}
Counts objects size (in bytes) for each type.
Note that the returned size may not be accurate, so it should only be used as a hint. Specifically, the size for T_DATA may be inaccurate because these are custom objects defined in Ruby and native extensions and so they may not accurately report their memory size.
It returns a hash that looks like:
{TOTAL: 1461154, T_CLASS: 158280, T_MODULE: 20672, T_STRING: 527249, ...}
The contents of the returned hash are implementation specific and may be changed in future versions without notice.
If the optional argument, result_hash, is given, it is overwritten and returned. This is intended to avoid the probe effect.
This method is only expected to work with C Ruby.