Archive
This post is archived and may contain outdated information. It has been set to 'noindex' and should stop showing up in search results.
JavaScript Canvas - Using Object Pool To Reduce Game Garbage Collection and Stuttering
Feb 18, 2014ProgrammingComments (0)
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.
Comments (0)
Add a Comment


Please review the commenting policy prior to commenting.
No comments yet