Charles is a software engineer and college professor interested in technology, medicine, economics, and nutrition.
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:
- 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.
- 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.
- 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.
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.
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.
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
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().