javascript / expert
Snippet
Object Pooling for Garbage Collection Mitigation
In high-throughput Node.js applications, frequent object allocation leads to excessive Garbage Collection (GC) pauses. Object pooling reuses existing objects, significantly reducing memory churn and improving performance in systems like game engines or real-time data processors.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class ObjectPool {constructor(factory, size = 10) {this.factory = factory;this.pool = Array.from({ length: size }, () => this.factory());}acquire() {return this.pool.length > 0 ? this.pool.pop() : this.factory();}release(obj) {Object.keys(obj).forEach(key => obj[key] = null);this.pool.push(obj);}}const particlePool = new ObjectPool(() => ({ x: 0, y: 0, active: true }));const p = particlePool.acquire();particlePool.release(p);
nodejs
Breakdown
1
this.pool = Array.from({ length: size }, () => this.factory());
Pre-allocates a set number of objects in memory to avoid initial allocation spikes.
2
return this.pool.length > 0 ? this.pool.pop() : this.factory();
Returns an idle object from the stack or creates a new one if the pool is exhausted.
3
Object.keys(obj).forEach(key => obj[key] = null);
Cleans the object state before returning it to the pool to prevent memory leaks or state pollution.