>> ObjectSpace.count_objects
=> {:TOTAL=>30205, :FREE=>131, :T_OBJECT=>1550, :T_CLASS=>921, :T_MODULE=>31, :T_FLOAT=>7, :T_STRING=>18368, :T_REGEXP=>185, :T_ARRAY=>4
196, :T_HASH=>254, :T_STRUCT=>1, :T_BIGNUM=>3, :T_FILE=>9, :T_DATA=>1311, :T_MATCH=>84, :T_COMPLEX=>1, :T_NODE=>3121, :T_ICLASS=>32}
>> class MyClass ; end
=> nil
>> ObjectSpace.count_objects
=> {:TOTAL=>30205, :FREE=>203, :T_OBJECT=>1562, :T_CLASS=>923, :T_MODULE=>31, :T_FLOAT=>7, :T_STRING=>18333, :T_REGEXP=>185, :T_ARRAY=>4
274, :T_HASH=>268, :T_STRUCT=>1, :T_BIGNUM=>3, :T_FILE=>9, :T_DATA=>1320, :T_MATCH=>97, :T_COMPLEX=>1, :T_NODE=>2956, :T_ICLASS=>32}
>> MyClass = nil
(irb):4: warning: already initialized constant MyClass
(irb):2: warning: previous definition of MyClass was here
=> nil
>> ObjectSpace.count_objects
=> {:TOTAL=>30205, :FREE=>87, :T_OBJECT=>1572, :T_CLASS=>923, :T_MODULE=>31, :T_FLOAT=>7, :T_STRING=>18425, :T_REGEXP=>185, :T_ARRAY=>43
39, :T_HASH=>279, :T_STRUCT=>1, :T_BIGNUM=>3, :T_FILE=>9, :T_DATA=>1328, :T_MATCH=>107, :T_COMPLEX=>1, :T_NODE=>2876, :T_ICLASS=>32}
>> MyClass
=> nil
>> GC.start
=> nil
>> ObjectSpace.count_objects
=> {:TOTAL=>30205, :FREE=>7356, :T_OBJECT=>1549, :T_CLASS=>921, :T_MODULE=>31, :T_FLOAT=>7, :T_STRING=>14100, :T_REGEXP=>184, :T_ARRAY=>
3821, :T_HASH=>244, :T_STRUCT=>1, :T_BIGNUM=>3, :T_FILE=>5, :T_DATA=>1285, :T_MATCH=>8, :T_COMPLEX=>1, :T_NODE=>657, :T_ICLASS=>32}
>>
查看T_CLASS
对象,我们可以看到这些是计数。当我删除类并启动垃圾收集器时,它会再次减少计数。
保持不变的 TOTAL 值并不意味着没有创建对象,很明显,当您创建一个新对象(例如 MyClass)时,计数没有改变。这可能意味着它只是偶尔重新评估总数,而不是实时重新评估。
但是,通过一些数学运算,当我对这些值求和并删除 TOTAL 计数时,我得到了 TOTAL。count_objects
因此,当报告对象计数时,它看起来像是对象数量的计数,这是有道理的。