I get this result (Cf. https://ruby-doc.org/core-2.5.1/ObjectSpace.html#method-c-count_objects):
total = ObjectSpace.count_objects[:TOTAL]
new_object = "tonytonyjan"
ObjectSpace.count_objects[:TOTAL] - total # => 0
total = ObjectSpace.count_objects[:T_STRING]
new_object = "tonytonyjan"
ObjectSpace.count_objects[:T_STRING] - total # => 0
Please explain why the result is zero. Did new_object
die just after the initialization?
Rather rely on each_object
to give the status about live objects:
def foo
total = ObjectSpace.each_object(String).count
str = "kiddorails"
puts ObjectSpace.each_object(String).count - total
end
foo
#=> 1
Another thing to note: the above code snippet is not fullproof to give the detail about incremented String objects, since GC is enable and can kick in anytime. I would prefer this:
def foo
GC.enable # enables GC if not enabled
GC.start(full_mark: true, immediate_sweep: true, immediate_mark: false) # perform GC if required on current object space
GC.disable # disable GC to get the right facts below
total = ObjectSpace.each_object(String).count
100.times { "kiddorails" }
puts ObjectSpace.each_object(String).count - total
end
foo #=> 100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With