Skip to content

Pooling

Pooling means creating a small group of reusable objects ahead of time instead of creating a new object every time it is needed.

Think of a pool as a rack of spare equipment. When the game needs one, it takes an available item from the rack, uses it, and makes it available again when it is finished. This is useful for things that are created and thrown away often, such as particles, bullets, and enemies.

The games in this course make a new Particle for every burst and drop it once it fades. A pool would create a fixed number up front and reuse them instead:

this.pool = [];
for (let i = 0; i < this.size; i++) {
this.pool.push(new Particle());
}

To spawn a particle, take one that isn’t in use, reset it, and mark it active:

spawn(x, y) {
const particle = this.pool.find((particle) => !particle.isAlive);
if (!particle) {
return;
}
particle.reset(x, y);
particle.isAlive = true;
}

Update and render only the active particles. When a particle’s effect ends, it sets isAlive back to false, and the next spawn() can reuse it. If every particle is busy, this version skips the new one. A larger pool lets more particles show at once but holds more objects in memory, so choose a size that fits how busy the effect gets.

Pooling can reduce repeated setup work and garbage collection in busy parts of a game. However, always start with simple, readable code and add a pool when an object is created often enough to slow the game down.