Sub topic 16
Writing Engine-Friendly JavaScript Without Micro-Optimizing
This chapter assumes you already know the earlier ideas in the tutorial: hidden classes, inline cache states, type feedback, deoptimization, and elements kinds. It also assumes you can run Node.js with V8 flags. The goal here is to turn those ideas into a few habits. Most of them also make code easier to read. You do not need tricks that fight the language.
Profile First, Then Fix
Engine-friendly code only matters on hot paths. A hot path is code that runs often enough to be optimized. A function that runs once at startup gains nothing from a stable shape. Measure before you change anything.
Habit 1: Initialize Every Property in the Constructor
If you add properties conditionally, objects of one class end up with several hidden classes. Declare every field up front, in the same order, and use null or a default value as a placeholder.
// Unstable: some users get an extra transition.
class UserA {
constructor(name, isAdmin) {
this.name = name;
if (isAdmin) this.role = 'admin';
}
}
// Stable: every instance has the same shape.
class UserB {
constructor(name, isAdmin) {
this.name = name;
this.role = isAdmin ? 'admin' : null;
}
}
const users = [new UserB('ana', true), new UserB('bo', false)];
console.log(users.map(u => u.role)); // [ 'admin', null ]Class field declarations such as role = null; give the same result and document the shape for readers.
Habit 2: Use Map for Dynamic Keys, Not delete
Objects that work as dictionaries, where keys come and go at runtime, will end up in dictionary mode anyway. Use a Map for that job. For fixed-shape objects, set a value to undefined or null and do not delete it.
const sessions = new Map();
sessions.set('abc', { user: 'ana' });
sessions.delete('abc'); // fine: Map is built for this
console.log(sessions.size); // 0Habit 3: Keep Hot Call Sites Monomorphic Where It Is Cheap
If a hot function receives many object shapes, its inline caches become megamorphic. Usually the fix is to build those objects with one factory or class, not to rewrite the function. Do not split a function into copies just to chase monomorphism unless a profile shows that this access is the bottleneck.
Habit 4: Keep Types and Arrays Consistent
| Pattern | Problem | Alternative |
|---|---|---|
| A number variable that sometimes holds a string | Breaks speculation, causes deopts | Convert at the boundary with `Number(x)` |
| `new Array(n)` filled out of order | Holey elements kind | `Array.from({ length: n }, () => 0)` or `push` |
| Mixing numbers and objects in one array | Generic `PACKED_ELEMENTS` | Separate arrays or typed arrays |
| `arr[arr.length + 5] = v` | Creates holes | Append with `push` |
What Not to Do
- Do not trade readability for guesses about the engine.
- Do not write micro-benchmarks in tight loops without using their results. The optimizer may delete the work you think you are measuring.
- Do not assume what is fast in V8 is fast in SpiderMonkey or JavaScriptCore. The broad habits carry over, but the details differ.
Exercise
A profile shows that the hot function render(item) is megamorphic at item.title. Items come from three API handlers that each build object literals with the same fields in different orders. What is the simplest engine-friendly fix?
Show answer
Build items through one shared factory function or class constructor that assigns the fields in a fixed order. All items then share one hidden class, and the access in render becomes monomorphic without any change to render itself.
Exercise
Why is replacing delete obj.cache with obj.cache = undefined usually better on a hot object, and when is a Map the better choice?
Show answer
Assigning undefined keeps the object's hidden class and fast properties, while delete can push the object into dictionary mode. A Map is better when keys are added and removed at runtime by design, because then the object is acting as a dictionary anyway.