H3XED

JavaScript Canvas - Using Object Pool To Reduce Game Garbage Collection and Stuttering

Feb 18, 2014   Programming   Nick Vogt   Comments
Please note that this post is over a year old and may contain outdated information.
If your JavaScript Canvas game suffers from intermittent stuttering, it may be the result of garbage collection. A lot of games utilize particles, bullets, and other objects that are created rapidly and then discarded. Storing these unused items in a pool, and then drawing from that pool the next time you need one, is one way to reduce stuttering and improve performance.

Here is an example not using an object pool:

var list = [];

function create() {
   list.push(new Object());
}

function destroy(i) {
   list.splice(i, 1);
}

The create function creates a new object in the list, while the destroy function splices an object from the list (with the index position of the one you want to destroy as i).

Now here is an object pool implementation:

var list = [];
var pool = [];

function create() {
   list.push(pool.length > 0 ? pool.pop() : new Object());
}

function destroy(i) {
   pool.push(list[i]);
   list.splice(i, 1);
}

Now the create function first checks if there are any unused objects in the pool, and pops one out. Otherwise it creates a new one as normal. The destroy function just adds the soon-to-be discarded object to the pool first (so it is not garbage collected and can be used later).

Object pools can be used with most programming languages and are not specific just to JavaScript. Furthermore, this is just one style of object pool. There is also a style where you pre-allocate all of your objects right up front, then only pull from the pool during the game.
Share This Post
Twitter

Comments (0)

Share This Post
Twitter
H3XED © Nick Vogt   RSS   Policies   Twitter