Data Structures and Algorithms with Object-Oriented Design Patterns in Ruby
next up previous index

Garbage Collection and the Other Kind of Heap

 

A Ruby object is an instance of a Ruby class. Every object instance in a Ruby program occupies some memory. The manner in which a Ruby object is represented in memory is left up to the implementor of the Ruby virtual machine and can vary from one implementation to another. However, an object's data typically occupy contiguous memory locations.

The region of memory in which objects are allocated dynamically is often called a heap . In Chapter gif we consider heaps and heap-ordered trees in the context of priority queue implementations. Unfortunately, the only thing that the heaps of Chapter gif and the heap considered here have in common is the name. While it may be possible to use a heap (in the sense of Definition gif) to manage a region of memory, typical implementations do not. In this context the technical meaning of the term heap is closer to its dictionary definition--``a pile of many things.''

The amount of memory required to represent a Ruby object is determined by its type. For example, four bytes are used typically to represent the value of a Fixnum and at least eight bytes are required to represent the value of a Float. In addition to the memory required for the value of an object, there is a fixed, constant amount of extra storage set aside in every object. This extra storage carries information used by the Ruby virtual machine to represent the class of the object and to aid the process of garbage collection.

When the Ruby virtual machine creates an object, it performs the following steps:

  1. An unused region of memory large enough to hold an instance of the desired class is found.
  2. All of the fields of the object are assigned their default initial values.
  3. The appropriate initialize method is run to initialize the object instance.
  4. A reference to the newly created object is returned.



next up previous index

Bruno Copyright © 2004 by Bruno R. Preiss, P.Eng. All rights reserved.