Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the total object count by `ObjectSpace.count_objects` not change?

Tags:

ruby

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?

like image 790
Weihang Jian Avatar asked Sep 19 '25 23:09

Weihang Jian


1 Answers

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
like image 84
kiddorails Avatar answered Sep 23 '25 02:09

kiddorails