加入我们,或者,欢迎回来。
您需要 登录 才可以下载或查看,没有帐号?注册会员
x
现在有点搞不懂一个对象什么时候会被回收了,于是写了一点代码。下面是Ruby2.0.0中的运行结果
def test GC.start arr = [] 100000.times { a_method(arr) } p arr.size end # test1 def a_method(arr) obj = 'temp' ObjectSpace.define_finalizer(obj, proc {|id| arr.push(id) }) end test #=> 0 # test2 def a_method(arr) ObjectSpace.define_finalizer('temp', proc {|id| arr.push(id) }) end test #=> 69872
def test
GC.start
arr = []
100000.times { a_method(arr) }
p arr.size
end
# test1
def a_method(arr)
obj = 'temp'
ObjectSpace.define_finalizer(obj, proc {|id| arr.push(id) })
end
test #=> 0
# test2
def a_method(arr)
ObjectSpace.define_finalizer('temp', proc {|id| arr.push(id) })
end
test #=> 69872
在test1中,虽然‘temp’字符串被赋给了变量obj,但是很快obj就出了作用域无法引用了。这个字符串应该是可以被回收的,可是最后却没有被回收。
在test2中,直接把'temp'作为参数传给了define_finalizer,这样倒是可以触发ruby的垃圾回收机制。
所以到底怎么样的对象可以触发ruby的垃圾回收?我以前一直觉得,当一个对象不被任何东西引用的时候就可以被回收了。但是test1证明似乎不是这样?求科普~~ |