From: Peter Zotov Date: 2012-05-28T20:56:31+09:00 Subject: Re: Garbage Collector(GC) and nil Damián M. González писал 27.05.2012 18:10: > Hello fellows, I'm wondering if I should set to nil any variables > that I > will not use anymore for the sake of save memory system, I didn't see > this way of work but I'm curious of what you can say. > I'm not sure about how GC works, tell me if I'm wrong: the GC will > erase in memory those "labels" that are pointing to nil, so, if I set > to > nil any variables, that space in memory will be free again. > I'll aprreciate any explanation. Ruby MRI (other implementations work in a somewhat similar way) uses mark-and-sweep garbage collector. When there is not enough memory, Ruby "marks" all objects in the global scope, i.e. global variables, constant contents and toplevel objects. Then it iterates through all marked objects and marks all objects the marked objects refer to. Ruby continues this cycle until no more objects are marked. Then it deallocates each non-marked object, because if there's no references to an object, there is no way to access it and it's not worth keeping. Long story short, when you set a reference (e.g. an instance variable) to nil, you remove a reference to whatever was stored there. If there are no other references, the object will be destroyed. -- WBR, Peter Zotov.