Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

Garbage Collection and the Other Kind of Heap

 

A C# object is an instance of a class, an array instance, or a delegate . Every object instance in a C# program occupies some memory. The manner in which a C# object is represented in memory is left up to the implementor of the common language runtime and, in principle, can vary from one implementation to another. However, object 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 C# object is determined by the number and the types of its fields. For example, fields of the C# simple types, occupy between one and sixteen bytes. E.g., bool occupies one byte; char, short, and ushort occupy two bytes; int, uint, and float occupy four bytes; long, ulong, and double occupy eight bytes; and decimal occupies sixteen bytes. A field which refers to an object or to an interface typically requires only four bytes.

In addition to the memory required for the fields of an object, there is a fixed, constant amount of extra storage set aside in every object (eight bytes). This extra storage carries information used by the common language runtime to make sure that object is used correctly and to aid the process of garbage collection.

Every object in a C# program is created explicitly by invoking the new operator. Invoking the new operator causes the common language runtime to perform 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 constructor is run to initialize the object instance.
  4. A reference to the newly created object is returned.



next up previous contents index

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