Skip to content

Instantly share code, notes, and snippets.

@janroudaut
Forked from martinwells/gist:2968030
Last active December 17, 2015 22:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janroudaut/5686248 to your computer and use it in GitHub Desktop.
Save janroudaut/5686248 to your computer and use it in GitHub Desktop.
// declare bullet pools
var activeBullets = [];
var bulletPool = [];
// construct some bullets ready for use
for (var i=0; i < 20; i++)
bulletPool.push( new Bullet() );
// a constructor/factory function
function getNewBullet()
{
var b = null;
// check to see if there is a spare one
if (bulletPool.length > 0)
b = bulletPool.pop();
else
// none left, construct a new one
b = new Bullet();
// move the new bullet to the active array
activeBullets.push(b);
return b;
}
function freeBullet(b)
{
// find the active bullet and remove it
// NOTE: Not using indexOf since it wont work in IE8 and below
for (var i=0, l=activeBullets.length; i < l; i++)
if (activeBullets[i] == b)
array.slice(i, 1);
// return the bullet back into the pool
bulletPool.push(b);
}
@janroudaut
Copy link
Author

From http://buildnewgames.com/garbage-collector-friendly-code/

When you want to fire a bullet, instead of doing:

var b = new Bullet();

You use the factory function:

var b = getNewBullet();

This will avoid construction by just returning one of the pre-constructed objects from the array, or if there are none available, fall back to constructing another bullet - essentially automatically expanding the pool.

Once you’re done with the bullet, you need to return it to the pool:

if (bullet.collidingWith(enemyShip))  // boom!
  freeBullet(bullet); // return it to the pool

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment