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.
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.
Depends on whether we are talking instance variables or local
variables. Local variables are automatically out of scope once the
method terminates (either via return or throw). As Peter said, if
that was the last reference to an object it is read for collection.
When that happens is a different story.
If you have member variables which are not needed any more then you
can set them to nil. Usually though, most member variables are still
needed to represent state of an object and if the object itself is no
longer reachable then those references are not life any more - so
explicit "clearing" (via setting to nil) is not needed most of the
time.
Kind regards
robert
···
On Sun, May 27, 2012 at 4:10 PM, Damián M. González <lists@ruby-forum.com> wrote:
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.