Remove a class instance in Ruby?
I've read the notes on GC happening at an undetermined time after disconnecting any references by instance variables, but would the second line in the delete
method be foolish, unnecessary or thorough?
class MyClass
# new instances added to @@instances
...
开发者_StackOverflow def delete
@@instances.delete(self)
self.instance_variables.each{|v| self.instance_variable_set(v,nil)}
end
end
Unnecessary. If you really want to trigger GC, use GC.start
or ObjectSpace.garbage_collect
.
And because it can't be recommended often enough, once again:
http://viewsourcecode.org/why/hacking/theFullyUpturnedBin.html
The method delete
executes in the scope of the instance that is being removed from the @@instances
structure, hence it cannot be garbage collected. Something triggered that method to run, and that something is currently holding a reference to it, therefore it cannot be garbage collected until after the method has returned (and the reference to the object been cleared).
That being said, the second line is completely unnecessary. Even if one of the instance variables pointed back to the object itself the GC is clever enough to figure that out (or rather, it just ignores it since it's not a reference counting collector).
Don't try to manually manage memory, it will not pay off. Whether or not you clear the references to the objects in those instance variables the GC decides when they will be freed. If I interpret the idea of your code example correctly all references to the host object are cleared after delete
has run, and in that case it doesn't matter if its instance variables are cleared too, the objects will be just as eligible for garbage collection either way. Objects are GC'ed when they are no longer reachable, it does not matter if other unreachable objects have references to them.
精彩评论