我得到这个结果(请参阅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是不是在初始化之后就死了?
发布于 2018-06-01 14:34:22
而是依靠each_object提供有关活动对象的状态:
def foo
total = ObjectSpace.each_object(String).count
str = "kiddorails"
puts ObjectSpace.each_object(String).count - total
end
foo
#=> 1另一件需要注意的事情是:上面的代码片段不能提供关于增量字符串对象的详细信息,因为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 #=> 100https://stackoverflow.com/questions/50635865
复制相似问题