Sub topic 14
Writing Code That Allocates Less
Earlier chapters covered how V8 finds garbage and how to track down leaks. This chapter covers a separate problem. A program can have no leaks and still spend too much time in garbage collection because it creates short-lived objects faster than it needs to. The rate at which code creates objects is called allocation pressure. This chapter assumes you know generational collection (young and old generations, scavenges, promotion) and can read heap snapshots and allocation profiles from the earlier chapters.
Why Allocation Rate Matters
Allocating in V8 is cheap. The young generation uses bump-pointer allocation, so creating an object is usually just a pointer increment. The cost comes later. Each time the young generation fills up, V8 runs a scavenge. Objects that survive two scavenges are promoted to the old generation. A growing old generation eventually triggers a major mark-and-sweep cycle, and that cycle costs more even when it runs incrementally and concurrently.
Short-lived garbage is the cheapest kind, but it still costs something. More allocation means more frequent scavenges. Each scavenge pauses the main thread, briefly, and copies whatever happens to be alive at that moment. If objects live just long enough to be caught mid-use, they get promoted and become old-generation garbage, which costs more to collect.
Measuring Allocation First
The script below runs the same calculation two ways. Run each version with --trace-gc and compare how many scavenges it prints.
// alloc-compare.js
const N = 1_000_000;
const values = Array.from({ length: N }, (_, i) => i);
function chained(arr) {
return arr
.map((x) => x * 2)
.filter((x) => x % 3 === 0)
.reduce((sum, x) => sum + x, 0);
}
function singlePass(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
const x = arr[i] * 2;
if (x % 3 === 0) sum += x;
}
return sum;
}
const mode = process.argv[2] === "single" ? "single" : "chained";
const fn = mode === "single" ? singlePass : chained;
const start = performance.now();
let result = 0;
for (let run = 0; run < 20; run++) {
result = fn(values);
}
const ms = (performance.now() - start).toFixed(1);
console.log(`${mode}: result=${result}, ${ms} ms`);node --trace-gc alloc-compare.js chained
node --trace-gc alloc-compare.js singleThe chained version builds two intermediate arrays of up to a million elements on every run. You should see many Scavenge lines, and maybe some Mark-Compact lines, for it and few or none for the single pass. In real applications, use the Allocation sampling profile in DevTools (Memory panel) or node --inspect to find which functions allocate the most. Then optimize only those.
Techniques
Fuse Pipelines in Hot Paths
As shown above, every map, filter, or slice in a chain creates a new array. In a hot path over large data, combine the steps into one loop. Outside hot paths, keep the chain because it reads better. A middle option is a generator pipeline, but generators allocate iterator result objects, so they do not always save anything. Measure.
Write Into Existing Objects
Functions that return a new small object on each call create a lot of garbage when they are called millions of times, as in games, physics, or geometry code. A common alternative is to accept an out parameter.
function addNew(a, b) {
return { x: a.x + b.x, y: a.y + b.y };
}
function addInto(out, a, b) {
out.x = a.x + b.x;
out.y = a.y + b.y;
return out;
}
const a = { x: 1, y: 2 };
const b = { x: 3, y: 4 };
const scratch = { x: 0, y: 0 };
for (let i = 0; i < 1_000_000; i++) {
addInto(scratch, a, b); // no allocation per iteration
}
console.log(scratch, addNew(a, b));Hoist Closures and Constants Out of Loops
Each time a function expression or arrow function is evaluated, it creates a new closure object. Callbacks defined inside a loop or a frequently called function are allocated again on every pass.
const items = Array.from({ length: 1000 }, (_, i) => ({ id: i, score: i % 7 }));
// Allocates a new comparator closure on every call
function sortScoresSlow(list) {
return list.slice().sort((p, q) => p.score - q.score);
}
// One comparator, created once
const byScore = (p, q) => p.score - q.score;
function sortScoresFast(list) {
return list.slice().sort(byScore);
}
console.log(sortScoresSlow(items)[0].score, sortScoresFast(items)[0].score);The same applies to regular expression literals and option objects built in hot functions. Create them once at module scope.
Use Typed Arrays for Numeric Data
An array of a million { x, y, vx, vy } objects means a million heap objects, each with a header and pointers for the collector to trace. A struct-of-arrays layout stores each field in its own Float64Array. That gives four allocations in total. The collector does not need to scan the contents, because typed arrays hold raw numbers and no references.
const COUNT = 100_000;
const posX = new Float64Array(COUNT);
const posY = new Float64Array(COUNT);
const velX = new Float64Array(COUNT).fill(1.5);
const velY = new Float64Array(COUNT).fill(-0.5);
function step(dt) {
for (let i = 0; i < COUNT; i++) {
posX[i] += velX[i] * dt;
posY[i] += velY[i] * dt;
}
}
for (let frame = 0; frame < 60; frame++) step(1 / 60);
console.log(posX[0].toFixed(3), posY[0].toFixed(3));Typed arrays also store numbers without boxing them. A regular array that holds non-integer numbers may store each one as a separate heap number, depending on its elements kind.
Reuse Buffers
In I/O and parsing code, allocate one working buffer and reuse it. In Node.js, Buffer.allocUnsafe(size) skips zero-filling, but its old contents are unpredictable, so overwrite it before reading. Encoding APIs such as TextEncoder.prototype.encodeInto write into an array you provide, which avoids allocating a new one per call.
const encoder = new TextEncoder();
const scratch = new Uint8Array(1024);
function byteLength(str) {
const { written } = encoder.encodeInto(str, scratch);
return written; // valid while the string fits in the scratch buffer
}
console.log(byteLength("héllo")); // 6Object Pools, With Caution
An object pool keeps released objects and hands them out again instead of allocating new ones.
class Pool {
constructor(create, reset) {
this.create = create;
this.reset = reset;
this.free = [];
}
acquire() {
return this.free.length > 0 ? this.free.pop() : this.create();
}
release(obj) {
this.reset(obj);
this.free.push(obj);
}
}
const particles = new Pool(
() => ({ x: 0, y: 0, alive: false }),
(p) => { p.x = 0; p.y = 0; p.alive = false; }
);
const p = particles.acquire();
p.alive = true;
particles.release(p);
console.log(particles.free.length); // 1With a generational collector, pools often help less than you might expect, and they bring their own failure modes:
- Pooled objects live long, so they get promoted to the old generation. When an old pooled object is made to point at a new young object, the write barrier records that pointer, and scavenges must treat it as a root. That adds work.
- If code keeps using an object after releasing it, two owners end up mutating the same object. These bugs are hard to trace.
- The free list holds its peak size forever. Without a cap, a pool behaves like an unbounded cache.
Pools are worth it for objects that are expensive to build (large buffers, objects with heavy initialization) or for steady, very high allocation rates where GC pauses are measurable, such as a 60 fps render loop. For small plain objects, try escape-analysis-friendly code first.
Retention Gotchas That Look Like Allocation Problems
Some patterns allocate little but keep much more alive than expected:
- Sliced strings. V8 may represent
bigString.slice(a, b)as a pointer into the parent string. If you keep a short substring of a multi-megabyte string, the parent can stay alive. In a heap snapshot, look for asliced stringwhose retainer is a large parent. Keeping only what you need, for example by parsing into numbers or objects, avoids this. - Subarrays and views.
typedArray.subarray()andBuffer.prototype.subarray()share the parent's memory. Keeping a small view keeps the whole backing store alive. Useslice()on typed arrays when you need an independent copy. - Holey preallocation.
new Array(n)creates a holey array, which V8 handles with slower element access. Usually it is better topushinto an empty array or to usenew Array(n).fill(0), or a typed array when the size is fixed.
Choosing a Technique
| Technique | Helps when | Cost |
|---|---|---|
| Fuse `map`/`filter` chains | Large arrays in hot paths | Less declarative code |
| `out` parameters | Small results created millions of times and escaping | Mutable API, aliasing bugs |
| Hoist closures and constants | Callbacks or regexes created per call | Usually none |
| Typed arrays (struct-of-arrays) | Large numeric datasets | Fixed size, numbers only |
| Reused buffers | Encoding, parsing, I/O | Must track valid length |
| Object pools | Expensive objects, steady high rates | Promotion, use-after-release, retained peak |
Exercise
A function called 500,000 times per second returns { min, max } to its caller, which immediately reads both fields and discards the object. Profiling shows little allocation from it. Why might that be, and should you convert it to an out parameter?
Show answer
TurboFan's escape analysis has probably inlined the function into its caller and replaced the object with local variables, because the object never escapes. The allocation has been optimized away, so converting to an out parameter would make the API harder to use for no measurable gain. Leave it alone unless a profile shows otherwise.
Exercise
A team adds an unbounded object pool for small event objects. Their heap no longer drops after traffic spikes, and scavenges got slower. Explain both effects.
Show answer
The pool's free list keeps every object ever released, so memory stays at the peak size, the same way an unbounded cache does. The pooled objects were promoted to the old generation. When they are given references to new young objects, the write barrier records those old-to-young pointers, and each scavenge must process them as extra roots. Capping the pool or removing it fixes both effects.
Exercise
A log parser reads a 50 MB string, extracts a 20-character request ID from each line with slice, and stores the IDs in a Set. Memory stays near 50 MB after the source string goes out of scope. What is the likely cause, and how would you confirm it?
Show answer
The stored IDs are probably V8 sliced strings that point into the 50 MB parent, so the parent stays reachable. To confirm, take a heap snapshot, select one of the ID strings, and check its retainers: a large parent string retained through a sliced string confirms it. Storing a derived value that does not reference the parent, such as a parsed number or a freshly built string, releases the original.