Computer Programming - C-Like Garbage Collection and Object Pooling

Updated on October 11, 2016
charles griffiths profile image

Charles is a software engineer and college professor interested in technology, medicine, economics, and nutrition.

Source

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)
      idle.Pop();
  }

  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().

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, turbofuture.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://turbofuture.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)