Computer Programming - C-Like Garbage Collection and Object Pooling


How allocated memory should be freed is a subject of some debate among programmers in C-Like languages. In C and C++ freeing allocated memory is thought to be so important that it should be handled explicitly by the programmer using free/delete. In C# and Java freeing allocated memory is thought to be so important that it should be handled automatically using the Garbage Collector (GC).

GC makes memory management easier, but it has problems.

  • It uses more memory. The GC requires extra pointers and reference counts for each allocation in order to do its job properly.
  • Lower performance overall. The GC takes more time to do its work than a simple free or delete.
  • Performance spikes. When the GC runs, typically all other threads stop until GC is finished. This can cause skipped frames in a graphics application or unacceptable lag in time critical code.

More important, if you're using C# or Java the GC is part of your environment. In this article I want to show you how to take advantage of the GC and minimize the downsides. Let's get started.

First Option: Do Nothing

The simplest and easiest way to micromanage the GC is simply treat it as if it's not a problem. This works because most of the time it won't be a problem.

GC is only a problem if you allocate, free, and then reallocate thousands of the same object type in a short span of time.

Second Option: Don't Allocate So Much

Take a look at your code and think about where you could reuse variables or not use them at all.

  • The foreach construct allocates an object to keep track of its progress. Change it to a for.
  • Instead of creating an object for the return value of a function, sometimes you can create the object once, save it in a member variable, and return it multiple times.
  • Whenever possible, create objects outside of loops.

Third Option: Use an Object Pool

Using an Object Pool can increase speed at the expense of increased memory use and code complexity. By using an Object Pool, you're refusing some of the advantages of GC and regressing from C# or Java to the lower level control of C or C++. This power can make a huge difference if used wisely.

Here's what you want from an Object Pool:

  1. Simplicity. A simple interface will minimize the code impact. In particular, you do not generally need a way to traverse or visit all the objects stored in the pool.
  2. Speed. Saving time is what the pool is all about. It should be as fast as possible. A pool storing ten objects should not perform any differently than a pool storing ten million objects.
  3. Flexibility. The pool should allow you to preallocate or get rid of stored objects as desired.

With these points in mind, let's look at how we might implement an Object Pool in C#.

A Pool is a Stack

A Stack is a C# generic type that stores a collection of Objects. For our purposes, you can either add an Object to the Stack with Push() or remove an Object with Pop(). These two operations take constant time, meaning their performance doesn't change with the size of the collection.

public abstract class Pool
  public abstract Type Type { get; }

public class Pool<T> : Pool where T : new()
Stack<T> idle = new Stack<T>();
int max;

  public Pool( int max = 10000 )
    this.max = max;

  public T allocate()
    return (0 == idle.Count) ? new T() : idle.Pop();

  public void deallocate( T t )
    if (max > idle.Count)
      idle.Push( t );

  public void preallocate( int count )
    while (count > idle.Count)
      idle.Push( new T() );

  public void truncate( int save )
    while (save < idle.Count)

  public override Type Type
    get { return typeof(T); }

In C# you have to define the base class Pool in order to keep a collection of Pool<T> that have different T as we do below.

Using a Pool

Create a Pool as Pool tpool = new Pool<T>(). When you want a new object of type T, instead of saying T t = new T() you say T t = tpool.allocate(). When you're done with the object, put it back in the pool with tpool.deallocate( t ).

Put Pools in a Dictionary

Put all of your pools in a central location in a Dictionary with Type as the key.

static class PoolCentral
static Dictionary<Type,Pool> pools = new Dictionary<Type,Pool>();

  static public Pool<T> getPool<T>() where T : new()
    if (!pools.ContainsKey( typeof(T) ))
      pools[typeof(T)] = new Pool<T>();

    return (Pool<T>) pools[typeof(T)]; 

Unity Prefab Pools

If you're using Unity and you want to create prefab pools, you need to handle the situation a bit differently.

  • Use Object instead of the C# Type class.
  • Prefabs create a new Object with Instantiate() instead of new().
  • Call Destroy() to get rid of instantiated Objects instead of just leaving them for the GC.

Just add the following lines to PoolCentral, and create a GoPool class.

static Dictionary<Object,GoPool> goPools = new Dictionary<Object,GoPool>();

static public GoPool getPool( Object prefab )
  if (!goPools.ContainsKey( prefab ))
    goPools[prefab] = new GoPool();

  return goPools[prefab];

Note that GoPool doesn't have to be generic because a GoPool always stores Stacks of Objects returned from Object.Instantiate(), but you could make it generic for convenience and extra safety.

Unity C# Generic Object Pool

All Done

In Java you should be able to do the same thing using Class instead of the C# Type.

As a final word of caution, remember to initialize and clear pooled objects as appropriate. You may wish to define functions with these names in your pooled types, calling initialize() on the object after allocating it from the pool, and clear() before sending it back to the pool with deallocate(). Clear() should set any stray object references to null unless you wish to reuse them in the pooling process. You could even define a base class that contains clear() and (since it requires no parameters) call it automatically from Pool.deallocate().

More by this Author

  • Computer Programming - Advanced C

    In the final stages of programming mastery, you must come to appreciate the strengths and weaknesses of your chosen language. Even if you choose a modern variant, a complete knowledge of C is useful.

  • Computer Programming - Advanced C-Like

    You can program in C every day for years and never use all the features in the core language. Most problems don't require them, but if you're aware they exist you can learn more as needed.

  • Relational Databases and Information Systems

    Whether you want to use, design, or improve a database application, understanding a few key ideas such as data types, indexes, and normalization can help you identify and share system requirements.


No comments yet.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.

    Click to Rate This Article