我得到了这个结果(见证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
请解释结果为零的原因。初始化后new_object
是否死亡?
答案 0 :(得分:2)
而是依靠each_object
来提供有关活动对象的状态:
def foo
total = ObjectSpace.each_object(String).count
str = "kiddorails"
puts ObjectSpace.each_object(String).count - total
end
foo
#=> 1
另外需要注意的是:上面的代码片段并不是完全无法提供有关递增的String对象的详细信息,因为GC已启用并且可以随时启动。我更喜欢这个:
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