XNA Resource Pool

By on 1/5/2010

This is likely an old topic at this point, considering the XNA framework has been out for several years. However, I meant to follow up on the topic of Resource Pooling after I posted the presentation materials from my ONETUG presentation on XNA last February. This is a simple resource pool that you can use to mitigate memory allocation issues in the XNA framework.

The canonical example of where a pool is useful, is a game entity firing bullets.  If you simply create a new instance of a bullet each time you fire, you will soon run out of memory. To avoid allocating new memory each time, you can reuse bullets that have moved off-screen or have collided with something.  There are several implementations that have been posted online such as: These are great, they definitely do the job.  However, they have a common issue in that they want to take on too much responsibility. In both cases, the resource pool acts as an array to hold all known instances in addition to being concerned with object construction logic.

I wanted a simple resource pool which provided the functionality of providing a "new" instance of an object when I needed one. So I created my own; The basic design is that there are only two methods: "New", and "Return".  The new method returns a new instance that is ready to use, while the return method adds a previously obtained object back into the pool.
using System;
using System.Collections.Generic;

namespace Scurvy { public class Pool<T> where T : class, new() { private Queue<T> queue; private Action<T> newRoutine;

public Pool(int capacity) { this.queue = new Queue<T>(capacity); }

public Pool() { this.queue = new Queue<T>(); }

public Pool(Action<T> newRoutine) : this() { this.newRoutine = newRoutine; }

public int Count { get { return this.queue.Count; } }

public T New() { T item;

item = queue.Count > 0 ? queue.Dequeue() : new T(); if (this.newRoutine != null) this.newRoutine(item);

return item; }

public void Return(T item) { queue.Enqueue(item); } } }
An interesting feature of this pool is that you can control the object initialization logic by providing a simple lambda to the constructor. Any initialization logic (such as resetting "isdead" fields, or resetting positions) can be done there and it will be executed for each new instance.

I'd love to get feedback on this class if you end up using it in a project. Thanks!

See more in the archives