Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Class object garbage collection

Tags:

In ruby all classes are objects of class Class. Since classes are also objects, does a Ruby VM follow the same Garbage Collection strategy for class objects? What determines that a class object is safe for garbage collection?

like image 586
Vaibhav Gumashta Avatar asked Feb 15 '10 09:02

Vaibhav Gumashta


People also ask

Does Ruby do garbage collection?

The Ruby Garbage Collector module is an interface to Ruby's mark and sweep garbage collection mechanism. While it runs automatically in the background when needed, the GC module lets you call the GC manually whenever required and gain insights into how garbage collection cycles are running.

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.

What is memory allocation in Ruby?

For Dynamic Memory allocation, the Ruby program uses Heap memory and the basic unit of the heap is a slot. Here, each slot occupies a value which is known as RVALUE. This RVALUE comprises 40 bytes and a container for objects of all types (Array, String, Class).

Does OCaml have garbage collection?

Garbage collection, reference counting, explicit allocation. As with all modern languages, OCaml provides a garbage collector so that you don't need to explicitly allocate and free memory as in C/C++.


1 Answers

An even more concrete example, similar to Andrew Cholakian's answer is to use ObjectSpace. For example:

2.1.1 :001 > ObjectSpace.count_objects[:T_CLASS]  => 884  2.1.1 :002 > 10000.times { Class.new }  => 10000  2.1.1 :003 > ObjectSpace.count_objects[:T_CLASS]  => 20884  2.1.1 :004 > GC.start  => nil  2.1.1 :005 > ObjectSpace.count_objects[:T_CLASS]  => 884  

This shows that anonymous classes (not saved in a constant anywhere or used by any instances of those classes) do indeed get garbage collected.

like image 120
Matt Connolly Avatar answered Nov 14 '22 19:11

Matt Connolly