ObjectSpace - what is it and how do people use it?
-
21-12-2020 - |
Question
Ruby-doc has this description:
The ObjectSpace module contains a number of routines that interact with the garbage collection facility and allow you to traverse all living objects with an iterator.
ObjectSpace also provides support for object finalizers, procs that will be called when a specific object is about to be destroyed by garbage collection.
Can anyone explain this in a simpler language, if not, atleast provide info on where this is used?
Solution
A garbage collector is a construct in languages with managed memory. It is the thing that manages the memory. Essentially, it's the job of the garbage collector to figure out when a piece of memory that has been allocated is no longer needed, and deallocate it.
When you're using a language with a garbage collector, there are certain things you might want to do:
- Run a method whenever a piece of memory is freed
- Count all instances of a class that are currently taking up memory
- Count all instances of all classes
ObjectSpace gives you access to do things of this nature. Essentially, it's a way to get access to anything and everything that's currently using allocated memory.
OTHER TIPS
For example, to count number of instances of some class:
class Examp
def self.obj_count
count = 0
ObjectSpace.each_object(self) do |b|
count += 1
end
return count
end
end
a = Examp.new
b = Examp.new
c = Examp.new
puts Examp.obj_count #=> 3
I know about class variables, bit it is only example of usage. It can be usefull every time when you want to perform some action on each instance of the class.
A real-world usage of ObjectSpace
is to derive the full class hierarchy of Exceptions.