class method
ObjectSpace.count_objects
(?::Hash[::Symbol, ::Integer] result_hash) -> ::Hash[::Symbol, ::Integer]
ObjectSpace.count_objects([result_hash]) → hash
gc.c
View on GitHub ↗
static VALUE
count_objects(int argc, VALUE *argv, VALUE os)
{
struct count_objects_data data = { 0 };
VALUE hash = Qnil;
VALUE types[T_MASK + 1];
if (rb_check_arity(argc, 0, 1) == 1) {
hash = argv[0];
if (!RB_TYPE_P(hash, T_HASH))
rb_raise(rb_eTypeError, "non-hash given");
}
for (size_t i = 0; i <= T_MASK; i++) {
// type_sym can allocate an object,
// so we need to create all key symbols in advance
// not to disturb the result
types[i] = type_sym(i);
}
// Same as type_sym, we need to create all key symbols in advance
VALUE total = ID2SYM(rb_intern("TOTAL"));
VALUE free = ID2SYM(rb_intern("FREE"));
rb_gc_impl_each_object(rb_gc_get_objspace(), count_objects_i, &data);
if (NIL_P(hash)) {
hash = rb_hash_new();
}
else if (!RHASH_EMPTY_P(hash)) {
rb_hash_stlike_foreach(hash, set_zero, hash);
}
rb_hash_aset(hash, total, SIZET2NUM(data.total));
rb_hash_aset(hash, free, SIZET2NUM(data.freed));
for (size_t i = 0; i <= T_MASK; i++) {
if (data.counts[i]) {
rb_hash_aset(hash, types[i], SIZET2NUM(data.counts[i]));
}
}
return hash;
}
Counts all objects grouped by type.
It returns a hash, such as:
Example
{
:TOTAL=>10000,
:FREE=>3011,
:T_OBJECT=>6,
:T_CLASS=>404,
# ...
}
The contents of the returned hash are implementation specific. It may be changed in future.
The keys starting with :T_ means live objects. For example, :T_ARRAY is the number of arrays. :FREE means object slots which is not used now. :TOTAL means sum of above.
If the optional argument result_hash is given, it is overwritten and returned. This is intended to avoid probe effect.
Example
h = {} ObjectSpace.count_objects(h) puts h # => { :TOTAL=>10000, :T_CLASS=>158280, :T_MODULE=>20672, :T_STRING=>527249 }
This method is only expected to work on C Ruby.
See also
.count_nodes
.count_objects_size
.count_imemo_objects
.count_symbols
also in
4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0