开发者

Ruby Class object garbage collection

开发者 https://www.devze.com 2022-12-20 08:45 出处:网络
In ruby all classes are objects of class Class. Since classes are also objects, does a Ruby VM follow the same Garbage Collection 开发者_如何学编程strategy for class objects? What determines that a cl

In ruby all classes are objects of class Class. Since classes are also objects, does a Ruby VM follow the same Garbage Collection 开发者_如何学编程strategy for class objects? What determines that a class object is safe for garbage collection?


An even more concrete example, similar to Andrew Cholakian's answer is to use ObjectSpace. For example:

2.1.1 :001 > ObjectSpace.count_objects[:T_CLASS]
 => 884 
2.1.1 :002 > 10000.times { Class.new }
 => 10000 
2.1.1 :003 > ObjectSpace.count_objects[:T_CLASS]
 => 20884 
2.1.1 :004 > GC.start
 => nil 
2.1.1 :005 > ObjectSpace.count_objects[:T_CLASS]
 => 884 

This shows that anonymous classes (not saved in a constant anywhere or used by any instances of those classes) do indeed get garbage collected.


I tested this out, the answer is it looks like it does.

irb(main):001:0> x = [] #Memory Usage = 12MB
=> []
irb(main):002:0> 120000.times {x << Class.new} #Memory usage now at 41 MB
=> 120000
irb(main):013:0> x = []
=> []
irb(main):011:0> GC.start() #Memory usage now at 13MB
=> nil


When there is nothing linking to the object, then it's safe to get rid of it. As far as -when- garbage collection is run, that is beyond my knowledge.


I have no idea what the answer is, but could you not find out by experimentation? Have a look at the pickaxe. I'm sure that this is a very naive test, and someone can do better, but you get the idea:

puts "program start"    
include ObjectSpace

class SfbdTest
   def initialize(a)
      @a = a
   end
end
define_finalizer(SfbdTest, proc{|id| puts "GC on class"} )

puts "creating instance"
x = SfbdTest.new(1)
define_finalizer(x, proc{|id| puts "GC on instance"} )

puts "zombie-ing instance"
x = nil

puts "forcing GC"
GC.start()

puts "program end"

Produces:

sfbd@thing:~$ ruby -w test.rb
program start
creating instance
zombie-ing instance
forcing GC
program end
GC on instance
GC on class
sfbd@thing:~$ 

Looks like it needs a thread, but unfortunately I'm supposed to be working, sorry...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号