Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are constants garbage collected in Ruby?

  1. When does the Class object assigned to a constant get garbage collected? E.g.

    class Foo; end
    Bar = Class.new {}
    
  2. 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..)

like image 718
Harish Shetty Avatar asked Nov 23 '13 20:11

Harish Shetty


People also ask

Is Ruby 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).

What is garbage collection in CLR?

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.

How does memory management work in Ruby?

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.


1 Answers

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).

like image 172
Andrew Marshall Avatar answered Sep 28 '22 00:09

Andrew Marshall