Sub topic 16
Writing Engine-Friendly JavaScript Without Micro-Optimizing
This chapter assumes you have read the earlier chapters on hidden classes, inline caches, type feedback, deoptimization, and elements kinds. It also assumes you can run Node.js scripts with flags. Here we turn those mechanisms into a small set of habits. We also cover when to apply them, which in most code is only after a profiler points at a hot path.
The Working Model: Stability Over Cleverness
The optimizations in earlier chapters reward predictable code. The engine works best when three things stay stable:
- Shape stability. Objects that flow through the same code have the same hidden class.
- Type stability. A variable, parameter, or return value keeps one kind of value, such as always a small integer or always a string.
- Elements stability. An array holds one kind of value and has no holes.
These habits cost almost nothing to write. Clever tricks are a different matter. Hand-unrolled loops, bitwise hacks, and caching array.length are often useless with modern engines, and some make code slower or harder to read. The goal is to avoid fighting the engine. You don't need to outsmart it.
Habit 1: Initialize Every Field in the Constructor
If you add properties conditionally or later, objects of the same "type" end up with different hidden classes. Then every call site that touches them gets more polymorphic. Declare every field up front, in a fixed order, even if the starting value is null.
// Unstable: shape depends on which branch ran and when.
function makeUserLoose(name, email) {
const u = { name };
if (email) u.email = email;
return u;
}
// Stable: every instance has the same fields in the same order.
class User {
constructor(name, email = null) {
this.name = name;
this.email = email;
this.lastLogin = null; // assigned later, but declared now
}
}
const users = [new User('ana', '[email protected]'), new User('bo')];
users[1].lastLogin = Date.now(); // updates a value, no shape change
console.log(users);Class field declarations (lastLogin = null; in the class body) give the same benefit. They also document the object's layout in one place.
Habit 2: Use the Right Container for Dynamic Keys
Objects with a fixed set of known keys are what hidden classes are built for. Objects used as hash maps, where keys come from user input or data and get added and removed often, are not. They create long transition chains or fall into dictionary mode. When keys are dynamic, use Map.
// Counting words: keys are unknown in advance.
function countWords(text) {
const counts = new Map();
for (const word of text.toLowerCase().split(/\W+/)) {
if (!word) continue;
counts.set(word, (counts.get(word) ?? 0) + 1);
}
return counts;
}
const counts = countWords('the cat and the hat and the bat');
console.log(counts.get('the')); // 3
counts.delete('cat'); // fine: Map is designed for deletion
console.log([...counts.keys()]);Use the same rule for removal. On a fixed-shape object, set a field to null rather than using delete. If you need delete all the time, the data probably belongs in a Map or Set.
Habit 3: Normalize Data at the Boundary
Data from JSON, databases, or third-party APIs often arrives with optional fields, varying key order, or mixed types. If those raw objects flow straight into hot code, every call site sees many shapes. Convert them once, where they enter your program.
class Order {
constructor(id, amount, currency) {
this.id = id;
this.amount = amount;
this.currency = currency;
}
static fromJSON(raw) {
return new Order(
String(raw.id),
Number(raw.amount ?? 0),
raw.currency ?? 'USD'
);
}
}
const payload = '[{"amount":"12.5","id":1},{"id":2,"currency":"EUR","amount":3}]';
const orders = JSON.parse(payload).map(Order.fromJSON);
function total(list) {
let sum = 0;
for (const o of list) sum += o.amount; // monomorphic: every o is an Order
return sum;
}
console.log(total(orders)); // 15.5This step also validates input at a trust boundary. Here the correctness benefit and the performance benefit point the same way.
Habit 4: Keep Functions Type-Stable
A function that returns different types depending on the path makes its callers polymorphic. It also invites deoptimization when the rarer path finally runs. Pick one return type and signal failure some other way.
| Pattern | Problem | Steadier alternative |
|---|---|---|
| Return a number or `false` | Callers see mixed types | Return a number, or `-1`, or `NaN` |
| Return an object or a string error | Shapes and types vary at call sites | Return `{ ok, value, error }` with all fields always present |
| Parameter is sometimes a string, sometimes an array | Branches and polymorphic access inside | Two functions, or normalize the argument at entry |
| Numeric field that is sometimes `"42"` | String concatenation instead of addition, deopts | Convert with `Number()` at the boundary |
// Every result has the same shape, whatever the outcome.
function parsePort(input) {
const n = Number.parseInt(input, 10);
if (Number.isInteger(n) && n > 0 && n < 65536) {
return { ok: true, value: n, error: null };
}
return { ok: false, value: 0, error: `invalid port: ${input}` };
}
console.log(parsePort('8080'));
console.log(parsePort('abc'));Habit 5: Keep Arrays Packed and Homogeneous
Elements kinds only move toward more general kinds, so one stray value can make an array slower to access for the rest of its life. A few rules cover most cases:
- Build arrays by pushing or with
Array.from, not by writing at large indexes. - Avoid
new Array(n)followed by filling out of order. It starts out holey.Array.from({ length: n }, () => 0)ornew Array(n).fill(0)gives you values from the start (fillkeeps the holey kind but leaves no actual holes). - Don't mix numbers and strings in an array of numbers. Don't store
undefinedas a placeholder in numeric arrays. - For large numeric data, use typed arrays such as
Float64Array. Their element type is fixed by construction.
const n = 1_000_000;
const samples = new Float64Array(n);
for (let i = 0; i < n; i++) samples[i] = Math.sin(i);
let max = -Infinity;
for (let i = 0; i < n; i++) if (samples[i] > max) max = samples[i];
console.log(max.toFixed(6));Common Errors
- Optimizing without profiling. Run
node --cpu-prof app.jsand open the.cpuprofilefile in Chrome DevTools first. Most time often goes to I/O, an O(n²) loop, or extra allocation, not to inline cache misses. - Trusting microbenchmarks. A tight loop around one function trains the engine on a single shape. Production traffic is messier. The optimizer can also remove work whose result is unused. Always consume results, warm up, and test with realistic data.
- Treating native syntax as a test.
%HaveSameMapand%HasFastPropertiesare diagnostic tools. Their behavior can change between V8 versions, so don't build checks around them. - Applying V8 folklore everywhere. Advice such as "avoid
try/catch" or "avoidforEach" was true for older compilers and is mostly false now. Re-measure on the Node.js version you actually ship. - Sacrificing readability. If a change makes code harder to understand and the profiler doesn't show a gain, revert it.
Measuring a Change Honestly
When you do change hot code, compare before and after under the same conditions:
// Run with: node bench.js
const { performance } = require('node:perf_hooks');
function bench(label, fn, iterations = 5) {
fn(); // warm-up run so the optimizing tiers can kick in
const times = [];
for (let i = 0; i < iterations; i++) {
const t0 = performance.now();
const result = fn();
times.push(performance.now() - t0);
if (result === Symbol.for('never')) console.log('unreachable'); // keep result live
}
times.sort((a, b) => a - b);
console.log(`${label}: median ${times[Math.floor(times.length / 2)].toFixed(2)} ms`);
}
const mixed = Array.from({ length: 200_000 }, (_, i) =>
i % 2 ? { x: i, y: i } : { y: i, x: i }
);
const uniform = Array.from({ length: 200_000 }, (_, i) => ({ x: i, y: i }));
const sumX = (list) => { let s = 0; for (const o of list) s += o.x; return s; };
bench('mixed shapes', () => sumX(mixed));
bench('uniform shapes', () => sumX(uniform));With only two shapes, the gap may be small, because a polymorphic inline cache handles two shapes well. That result is useful in itself. Fix instability when it pushes a site toward megamorphic or causes repeated deoptimization. Don't fix it just because you can.
Exercise
A hot function render(item) receives items built in three places: a literal { title, body }, a literal { body, title }, and an object that starts as { title } and later gets body added. Profiling shows render is hot and --trace-deopt reports repeated deopts there. What single change addresses this, and why?
Show answer
Create all items through one constructor or factory (for example a class Item whose constructor assigns title then body). The three construction paths produce three hidden classes, which makes the property accesses in render polymorphic and destabilizes optimized code. One constructor gives every item the same shape, so the inline caches become monomorphic and the speculation holds.
Exercise
A teammate replaces cache[key] = value and delete cache[key] on a plain object, where keys are user IDs, with cache[key] = undefined to "avoid delete." Is this a good fix? What would you suggest?
Show answer
Not really. The object is still a hash map with dynamic keys, so it still grows a huge number of properties and will likely end up in dictionary mode anyway. It also leaks entries, because keys are never removed. Use a Map, which is designed for frequent insertion and deletion with arbitrary keys, and call map.delete(key).
Exercise
Why can a microbenchmark show a large speedup from making shapes uniform, while the same change shows no measurable gain in the production service?
Show answer
The microbenchmark isolates one hot loop and may exaggerate the inline cache cost. In production, total time is usually dominated by other work such as I/O, allocation, or algorithmic cost. The call site may also already be in a cheap polymorphic state. Only a profile of the real workload shows whether the change matters.