Ruby's ObjectSpace: A Challenge for the Managed Platforms

The Ruby language contains the built-in module ObjectSpace, which provides programmatic access to the entire world of living objects. For instance, in Ruby you can write:

ObjectSpace::each_object(Class) do |c|
 p c if c < Test::Unit::TestCase
 end

which will iterate over every instance of Class in the system and do something (in this case, print it out if it is a subclass of TestCase).

John Lam has mentioned to me that ObjectSpace is a particular challenge to IronRuby, as the obvious way to implement ObjectSpace is to hook into the garbage collector, which is not something that is allowed in the world of the CLR. Or in the world of the JVM, as Ola Bini discusses in this interesting post. Implementing ObjectSpace on the managed platforms (using WeakReferences) involves a huge performance hit (Bini talks of measuring several dozen percentage points worth of penalty). He additionally shows some code that works around the obvious ObjectSpace use-case.