The objspace library extends the ObjectSpace module and adds several methods to get internal statistic information about object/memory management.

You need to require 'objspace' to use this extension module.

Generally, you SHOULD NOT use this library if you do not know about the MRI implementation. Mainly, this library is for (memory) profiler developers and MRI developers who need to know about MRI memory usage.

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 after a specific object was destroyed by garbage collection. See the documentation for ObjectSpace.define_finalizer for important information on how to use this method correctly.

a = "A"
b = "B"

ObjectSpace.define_finalizer(a, proc {|id| puts "Finalizer one on #{id}" })
ObjectSpace.define_finalizer(b, proc {|id| puts "Finalizer two on #{id}" })

a = nil
b = nil

produces:

Finalizer two on 537763470
Finalizer one on 537763480
Class Methods

Returns the class for the given object.

class A
  def foo
    ObjectSpace::trace_object_allocations do
      obj = Object.new
      p "#{ObjectSpace::allocation_class_path(obj)}"
    end
  end
end

A.new.foo #=> "Class"

See ::trace_object_allocations for more information and examples.

Returns garbage collector generation for the given object.

class B
  include ObjectSpace

  def foo
    trace_object_allocations do
      obj = Object.new
      p "Generation is #{allocation_generation(obj)}"
    end
  end
end

B.new.foo #=> "Generation is 3"

See ::trace_object_allocations for more information and examples.

Returns the method identifier for the given object.

class A
  include ObjectSpace

  def foo
    trace_object_allocations do
      obj = Object.new
      p "#{allocation_class_path(obj)}##{allocation_method_id(obj)}"
    end
  end
end

A.new.foo #=> "Class#new"

See ::trace_object_allocations for more information and examples.

Returns the source file origin from the given object.

See ::trace_object_allocations for more information and examples.

Returns the original line from source for from the given object.

See ::trace_object_allocations for more information and examples.

Returns a hash containing the number of objects for each T_IMEMO type. The keys are Symbol objects of the T_IMEMO type name. T_IMEMO objects are Ruby internal objects that are not visible to Ruby programs.

ObjectSpace.count_imemo_objects
# => {imemo_callcache: 5482, imemo_constcache: 1258, imemo_ment: 13906, ... }

If the optional argument result_hash is given, it is overwritten and returned. This is intended to avoid the probe effect.

This method is intended for developers interested in performance and memory usage of Ruby programs. The contents of the returned hash is implementation specific and may change in the future.

This method is only expected to work with C Ruby.

Counts all objects grouped by type.

It returns a hash, such as:

{
  :TOTAL=>10000,
  :FREE=>3011,
  :T_OBJECT=>6,
  :T_CLASS=>404,
  # ...
}

The contents of the returned hash are implementation specific. It may be changed in future.

The keys starting with :T_ means live objects. For example, :T_ARRAY is the number of arrays. :FREE means object slots which is not used now. :TOTAL means sum of above.

If the optional argument result_hash is given, it is overwritten and returned. This is intended to avoid probe effect.

h = {}
ObjectSpace.count_objects(h)
puts h
# => { :TOTAL=>10000, :T_CLASS=>158280, :T_MODULE=>20672, :T_STRING=>527249 }

This method is only expected to work on C Ruby.

Counts objects size (in bytes) for each type.

Note that this information is incomplete. You need to deal with this information as only a HINT. Especially, total size of T_DATA may be wrong.

It returns a hash as:

{:TOTAL=>1461154, :T_CLASS=>158280, :T_MODULE=>20672, :T_STRING=>527249, ...}

If the optional argument, result_hash, is given, it is overwritten and returned. This is intended to avoid probe effect.

The contents of the returned hash is implementation defined. It may be changed in future.

This method is only expected to work with C Ruby.

Returns a hash containing the number of objects for each Symbol type.

The types of Symbols are the following:

  • mortal_dynamic_symbol: Symbols that are garbage collectable.

  • immortal_dynamic_symbol: Symbols that are objects allocated from the garbage collector, but are not garbage collectable.

  • immortal_static_symbol: Symbols that are not allocated from the garbage collector, and are thus not garbage collectable.

  • immortal_symbol: the sum of immortal_dynamic_symbol and immortal_static_symbol.

If the optional argument result_hash is given, it is overwritten and returned. This is intended to avoid the probe effect.

This method is intended for developers interested in performance and memory usage of Ruby programs. The contents of the returned hash is implementation specific and may change in the future.

This method is only expected to work with C Ruby.

Returns a hash containing the number of objects for each T_DATA type. The keys are Class objects when the T_DATA object has an associated class, or Symbol objects of the name defined in the rb_data_type_struct for internal T_DATA objects.

ObjectSpace.count_tdata_objects
# => {RBS::Location => 39255, marshal_compat_table: 1, Encoding => 103, mutex: 1, ... }

If the optional argument result_hash is given, it is overwritten and returned. This is intended to avoid the probe effect.

This method is intended for developers interested in performance and memory usage of Ruby programs. The contents of the returned hash is implementation specific and may change in the future.

This method is only expected to work with C Ruby.

Adds a new finalizer for obj that is called when obj is destroyed by the garbage collector or when Ruby shuts down (which ever comes first).

With a block given, uses the block as the callback. Without a block given, uses a callable object finalizer as the callback. The callback is called when obj is destroyed with a single argument id which is the object ID of obj (see Object#object_id).

The return value is an array [0, callback], where callback is a Proc created from the block if one was given or finalizer otherwise.

Note that defining a finalizer in an instance method of the object may prevent the object from being garbage collected since if the block or finalizer refers to obj then obj will never be reclaimed by the garbage collector. For example, the following script demonstrates the issue:

class Foo
  def define_final
    ObjectSpace.define_finalizer(self) do |id|
      puts "Running finalizer for #{id}!"
    end
  end
end

obj = Foo.new
obj.define_final

There are two patterns to solve this issue:

  • Create the finalizer in a non-instance method so it can safely capture the needed state:

    class Foo
      def define_final
        ObjectSpace.define_finalizer(self, self.class.create_finalizer)
      end
    
      def self.create_finalizer
        proc do |id|
          puts "Running finalizer for #{id}!"
        end
      end
    end
    
  • Use a callable object:

    class Foo
      class Finalizer
        def call(id)
          puts "Running finalizer for #{id}!"
        end
      end
    
      def define_final
        ObjectSpace.define_finalizer(self, Finalizer.new)
      end
    end
    

Note that finalization can be unpredictable and is never guaranteed to be run except on exit.

Calls the block once for each living, nonimmediate object in this Ruby process. If module is specified, calls the block for only those classes or modules that match (or are a subclass of) module. Returns the number of objects found. Immediate objects (such as Fixnums, static Symbols true, false and nil) are never returned.

If no block is given, an enumerator is returned instead.

Job = Class.new
jobs = [Job.new, Job.new]
count = ObjectSpace.each_object(Job) {|x| p x }
puts "Total count: #{count}"

produces:

#<Job:0x000000011d6cbbf0>
#<Job:0x000000011d6cbc68>
 Total count: 2

Due to a current Ractor implementation issue, this method does not yield Ractor-unshareable objects when the process is in multi-Ractor mode. Multi-ractor mode is enabled when Ractor.new has been called for the first time. See bugs.ruby-lang.org/issues/19387 for more information.

a = 12345678987654321 # shareable
b = [].freeze # shareable
c = {} # not shareable
ObjectSpace.each_object {|x| x } # yields a, b, and c
Ractor.new {} # enter multi-Ractor mode
ObjectSpace.each_object {|x| x } # does not yield c

Alias of GC.start

MRI specific feature

Return internal class of obj.

obj can be an instance of InternalObjectWrapper.

Note that you should not use this method in your application.

MRI specific feature

Return internal super class of cls (Class or Module).

obj can be an instance of InternalObjectWrapper.

Note that you should not use this method in your application.

Return consuming memory size of obj in bytes.

Note that the return size is incomplete. You need to deal with this information as only a HINT. Especially, the size of T_DATA may not be correct.

This method is only expected to work with CRuby.

From Ruby 3.2 with Variable Width Allocation, it returns the actual slot size used plus any additional memory allocated outside the slot (such as external strings, arrays, or hash tables).

Returns the total memory size of all living objects in bytes.

ObjectSpace.memsize_of_all # => 12502001

If klass is given (which must be a Class or Module), returns the total memory size of objects whose class is, or is a subclass, of klass.

class MyClass; end
ObjectSpace.memsize_of_all(MyClass) # => 0
o = MyClass.new
ObjectSpace.memsize_of_all(MyClass) # => 40

Note that the value returned may be an underestimate of the actual amount of memory used. Therefore, the value returned should only be used as a hint, rather than a source of truth. In particular, the size of T_DATA objects may not be correct.

This method is only expected to work with C Ruby.

MRI specific feature

Return all reachable objects from ‘obj’.

This method returns all reachable objects from ‘obj’.

If ‘obj’ has two or more references to the same object ‘x’, then returned array only includes one ‘x’ object.

If ‘obj’ is a non-markable (non-heap management) object such as true, false, nil, symbols and Fixnums (and Flonum) then it simply returns nil.

If ‘obj’ has references to an internal object, then it returns instances of ObjectSpace::InternalObjectWrapper class. This object contains a reference to an internal object and you can check the type of internal object with ‘type’ method.

If ‘obj’ is instance of ObjectSpace::InternalObjectWrapper class, then this method returns all reachable object from an internal object, which is pointed by ‘obj’.

With this method, you can find memory leaks.

This method is only expected to work with C Ruby.

Example:

ObjectSpace.reachable_objects_from(['a', 'b', 'c'])
#=> [Array, 'a', 'b', 'c']

ObjectSpace.reachable_objects_from(['a', 'a', 'a'])
#=> [Array, 'a', 'a', 'a'] # all 'a' strings have different object id

ObjectSpace.reachable_objects_from([v = 'a', v, v])
#=> [Array, 'a']

ObjectSpace.reachable_objects_from(1)
#=> nil # 1 is not markable (heap managed) object
MRI specific feature

Return all reachable objects from root.

Starts tracing object allocations from the ObjectSpace extension module.

For example:

require 'objspace'

class C
  include ObjectSpace

  def foo
    trace_object_allocations do
      obj = Object.new
      p "#{allocation_sourcefile(obj)}:#{allocation_sourceline(obj)}"
    end
  end
end

C.new.foo #=> "objtrace.rb:8"

This example has included the ObjectSpace module to make it easier to read, but you can also use the ::trace_object_allocations notation (recommended).

Note that this feature introduces a huge performance decrease and huge memory consumption.

Clear recorded tracing information.

Starts tracing object allocations for GC debugging. If you encounter the BUG “… is T_NONE” (and so on) on your application, please try this method at the beginning of your app.

Starts tracing object allocations.

Stop tracing object allocations.

Note that if ::trace_object_allocations_start is called n-times, then tracing will stop after calling ::trace_object_allocations_stop n-times.

Removes all finalizers for obj.

Instance Methods

Dump the contents of a ruby object as JSON.

output can be one of: :stdout, :file, :string, or IO object.

  • :file means dumping to a tempfile and returning corresponding File object;

  • :stdout means printing the dump and returning nil;

  • :string means returning a string with the dump;

  • if an instance of IO object is provided, the output goes there, and the object is returned.

This method is only expected to work with C Ruby. This is an experimental method and is subject to change. In particular, the function signature and output format are not guaranteed to be compatible in future versions of ruby.

Dump the contents of the ruby heap as JSON.

output argument is the same as for dump.

full must be a boolean. If true, all heap slots are dumped including the empty ones (T_NONE).

since must be a non-negative integer or nil.

If since is a positive integer, only objects of that generation and newer generations are dumped. The current generation can be accessed using GC::count. Objects that were allocated without object allocation tracing enabled are ignored. See ::trace_object_allocations for more information and examples.

If since is omitted or is nil, all objects are dumped.

shapes must be a boolean or a non-negative integer.

If shapes is a positive integer, only shapes newer than the provided shape id are dumped. The current shape_id can be accessed using RubyVM.stat(:next_shape_id).

If shapes is false, no shapes are dumped.

To only dump objects allocated past a certain point you can combine since and shapes:

ObjectSpace.trace_object_allocations
GC.start
gc_generation = GC.count
shape_generation = RubyVM.stat(:next_shape_id)
call_method_to_instrument
ObjectSpace.dump_all(since: gc_generation, shapes: shape_generation)

This method is only expected to work with C Ruby. This is an experimental method and is subject to change. In particular, the function signature and output format are not guaranteed to be compatible in future versions of ruby.

Dump the contents of the ruby shape tree as JSON.

output argument is the same as for dump.

If since is a positive integer, only shapes newer than the provided shape id are dumped. The current shape_id can be accessed using RubyVM.stat(:next_shape_id).

This method is only expected to work with C Ruby. This is an experimental method and is subject to change. In particular, the function signature and output format are not guaranteed to be compatible in future versions of ruby.

Alias of GC.start