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

Reuse

Sometimes, a C# program will create many objects which are used only once. For example, a program may create an object in the body of a loop that is used to hold ``temporary'' information that is only required for the particular iteration of the loop in which it is created. Consider the following:

for (int i = 0; i < 1000000; ++i)
{
    SomeClass obj = new SomeClass(i);
    Console.WriteLine(obj);
}
This creates a million instances of the SomeClass class and prints them out. If the SomeClass class has a propery, say Value, that provides a set accessor, we can reuse an a single object instance like this:
SomeClass obj = new SomeClass();
for (int i = 0; i < 1000000; ++i)
{
    obj.Value = i;
    Console.WriteLine(obj);
}
Clearly, by reusing a single object instance, we have dramatically reduced the amount of garbage produced.


next up previous contents index

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