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