When does the Class
object assigned to a constant get garbage collected? E.g.
class Foo; end
Bar = Class.new {}
When does a constant declared inside an anonymous class/module get garbage collected? E.g.
foo = Class.new do
self::NAME = "Bar"
end
foo::NAME # Bar
foo = nil
GC.start
In the example above, will the constant NAME
declared inside the anonymous class be garbage collected? ( I am assuming the anonymous class will be garbage collected..)
Many modern programming languages manage memory for you, and Ruby is no different. Ruby manages memory usage using a garbage collector (also called gc).
In the common language runtime (CLR), the garbage collector (GC) serves as an automatic memory manager. The garbage collector manages the allocation and release of memory for an application. For developers working with managed code, this means that you don't have to write code to perform memory management tasks.
The Memory Profiler gem is an effective way of tracking the memory usage of ruby code. This command will send a bunch of requests to your application, and track memory usage over time. In case of a memory leak, the memory usage will keep on increasing over time.
It’s easy to boil this down to the very general case: if an object no longer has any references to it, it can be garbage collected. Note that I say object, not variable. Variables are not garbage collected, objects are.
Now let’s look at your given examples:
class Foo; end
Bar = Class.new {}
Instances of Class
will only be garbage collected if the constant they’re assigned to (if any) is reassigned to a different value (e.g. Bar = nil
) and there are no instances of that class and there are no Classes which inherit from it.
foo = Class.new do
self::NAME = "Bar"
end
foo::NAME # Bar
foo = nil
The values previously in foo
& foo::NAME
can be garbage collected if there were no other references to them (i.e. this snippet is the complete code).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With