Ruby Class object garbage collection

后端 未结 4 1401
不思量自难忘°
不思量自难忘° 2021-01-07 17:22

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

4条回答
  •  时光说笑
    2021-01-07 18:16

    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...

提交回复
热议问题