Sub topic 14
Writing Code That Allocates Less
This chapter assumes you know how V8 splits the heap into young and old generations, and that you can take an allocation profile in DevTools. Earlier chapters covered both. The focus here is practical: a few changes that make your code create fewer short-lived objects in places where speed matters.
Why allocation rate matters
Allocating an object in V8 is cheap. The engine bumps a pointer in the young generation. The cost comes later. Each time the young generation fills, a minor collection runs. Objects that survive several of these collections get promoted to the old generation, and major collections there cost more. The more garbage your code makes per second, the more often these collections run. Developers call this allocation pressure.
Most code never needs this kind of tuning. Profile first. Only rewrite a function after the allocation timeline shows it producing a lot of garbage on a hot path, such as an animation frame, a request handler, or a parser loop.
Technique 1: Skip intermediate arrays
Every call to map and filter returns a new array. If you chain them, each step allocates a full array that is thrown away right after.
const prices = Array.from({ length: 100_000 }, (_, i) => i % 50);
// Allocates two temporary arrays
const totalChained = prices
.filter((p) => p > 10)
.map((p) => p * 1.2)
.reduce((sum, p) => sum + p, 0);
// Allocates nothing beyond the result
let totalLoop = 0;
for (let i = 0; i < prices.length; i++) {
const p = prices[i];
if (p > 10) totalLoop += p * 1.2;
}
console.log(totalChained.toFixed(2), totalLoop.toFixed(2));Technique 2: Reuse output objects
A function that returns a fresh { x, y } on every call creates one object per call. In a per-frame calculation, you can have the caller pass in an object for the function to fill.
function midpointInto(out, a, b) {
out.x = (a.x + b.x) / 2;
out.y = (a.y + b.y) / 2;
return out;
}
const scratch = { x: 0, y: 0 };
const a = { x: 0, y: 0 };
const b = { x: 10, y: 4 };
for (let frame = 0; frame < 3; frame++) {
b.x += 1;
midpointInto(scratch, a, b);
console.log(scratch.x, scratch.y);
}The catch is that scratch gets overwritten on each call. Copy its values if you need to keep them.
Technique 3: Pool objects that you create often
An object pool keeps released objects so you can use them again instead of allocating new ones.
class ParticlePool {
constructor() {
this.free = [];
}
acquire(x, y) {
const p = this.free.pop() || { x: 0, y: 0, alive: false };
p.x = x;
p.y = y;
p.alive = true;
return p;
}
release(p) {
p.alive = false;
this.free.push(p);
}
}
const pool = new ParticlePool();
const p1 = pool.acquire(1, 2);
pool.release(p1);
const p2 = pool.acquire(5, 6);
console.log(p1 === p2); // true: the same object was reusedTechnique 4: Use typed arrays for numeric data
An array of a million { x, y } objects is a million separate heap objects. A Float64Array holds the same numbers in one contiguous buffer, so the GC has a single object to trace.
const count = 1_000_000;
const coords = new Float64Array(count * 2); // x at 2i, y at 2i+1
for (let i = 0; i < count; i++) {
coords[2 * i] = i;
coords[2 * i + 1] = i * 2;
}
console.log(coords[2 * 500], coords[2 * 500 + 1]); // 500 1000Other sources of hidden allocation
| Pattern | What gets allocated | Alternative on a hot path |
|---|---|---|
| Arrow function created inside a loop | A new closure per iteration | Define the function once, outside the loop |
| `str += piece` in a large loop | Intermediate strings | Collect the pieces in an array and call `join` once |
| `{ ...obj }` or `[...arr]` per call | A full copy | Mutate a local object you own |
| `arguments` or rest parameters in tiny helpers | An array per call | Use fixed parameters |
Exercise
A game calls getVelocity() 60 times per second for 2,000 entities, and each call returns a new { dx, dy } object. The allocation timeline shows steady sawtooth memory and frequent minor GCs. Name two ways to reduce the pressure and one risk that comes with each.
Show answer
(1) Pass in a reusable output object for the function to fill (the midpointInto pattern). The risk is that a caller keeps the reference and later sees it overwritten. (2) Store velocities in a Float64Array indexed by entity. The risk is less readable code and manual index bookkeeping. An object pool is another option, but it risks leaks or stale data if objects are released incorrectly.
Exercise
Why can an object pool make major GC slower even while it reduces minor GC frequency?
Show answer
Pooled objects survive many minor collections and get promoted to the old generation. That makes the old generation bigger, so each major collection has more live objects to mark.