Sub topic 8
Inline Caches: Remembering Where Properties Live
This chapter assumes you already know three things from earlier chapters. V8 compiles functions to bytecode and runs them in the Ignition interpreter. Every object has a hidden class, called a map in V8, that records which properties it has and where each one sits in memory. Adding properties moves an object along a chain of map transitions. Here we look at the mechanism that turns that layout information into fast property access: the inline cache.
The Problem: Lookups Are Expensive
Take an ordinary expression like o.x. In a statically typed language such as C, the compiler knows the type of o, so o.x becomes "load the value at offset 8 from the object's address". JavaScript gives the engine no such guarantee. Any object can reach o, and x can be stored on the object itself, on a prototype, as a getter, or nowhere at all.
A generic lookup for o.x has to do these steps:
- Read the map pointer from
o. - Search the map's descriptor array for the key
x. - If
xis found, read its offset and its kind (data field, constant, accessor). - If it is not found, move to
o's prototype and repeat. - Load the value, or call the getter.
Hidden classes make step 2 cheaper than a hash table lookup on every object. Even so, doing these steps on every execution of o.x inside a hot loop would waste most of the program's time. Inline caches avoid repeating the work.
The Idea: Cache the Answer at the Access Site
An inline cache (IC) is a small record attached to one property access in the source code. It stores the result of the last slow lookup at that location: "objects with map M keep x at offset 12." The next time the same line of code runs, the engine compares the incoming object's map with M. If they match, it loads directly from offset 12 and skips the search.
Two details make this work:
- The cache belongs to the site, not the object. Each
o.xin your source has its own cache. Two different functions that both read.xlearn separately. - The key is the map. Objects that share a map have the same layout, so one map comparison is enough to prove the cached offset is valid.
The word "inline" comes from early Smalltalk and Self implementations. They patched the cached check directly into the machine code at the call site. V8 now keeps the cached data in a side table, but the name stuck.
Where V8 Stores Inline Caches
In V8, every function has a feedback vector. A feedback vector is an array of slots, and each property access, store, call, or arithmetic operation in the function gets its own slot. The bytecode instruction for a property load names the slot it uses. You can see this yourself:
// Save as ic.js and run:
// node --print-bytecode --print-bytecode-filter=getX ic.js
function getX(o) {
return o.x;
}
for (let i = 0; i < 10; i++) {
getX({ x: i });
}The output includes a line like this (the exact format depends on your Node version):
GetNamedProperty a0, [0], [0]Older Node versions print LdaNamedProperty instead. The operands mean: load from argument a0, using property name constant [0] (the string "x"), with feedback slot [0]. The first time this runs, slot 0 is empty and the load misses. The IC miss handler, which is a call into the V8 runtime, does the full lookup and writes the map and offset into slot 0. Later executions hit.
The next chapter covers what the cache holds over time. In short, a slot can hold one map (monomorphic), a few maps (polymorphic), or give up and fall back to a global cache (megamorphic).
A Working Model in Plain JavaScript
The real IC lives inside V8, but the logic fits in a few lines. This toy model uses explicit shapes and slot arrays so you can watch hits and misses.
// toy-ic.js — run with: node toy-ic.js
class Shape {
constructor(keys) {
this.keys = keys;
this.offsets = new Map(keys.map((k, i) => [k, i]));
}
}
function makeObject(shape, values) {
return { shape, slots: values };
}
function slowLookup(obj, name) {
// Stands in for the descriptor search and prototype walk.
const offset = obj.shape.offsets.get(name);
if (offset === undefined) throw new Error(`no property ${name}`);
return offset;
}
function makeLoadIC(name) {
let cachedShape = null;
let cachedOffset = -1;
const stats = { hits: 0, misses: 0 };
function load(obj) {
if (obj.shape === cachedShape) {
stats.hits++;
return obj.slots[cachedOffset];
}
stats.misses++;
cachedOffset = slowLookup(obj, name);
cachedShape = obj.shape;
return obj.slots[cachedOffset];
}
return { load, stats };
}
const XY = new Shape(['x', 'y']);
const YX = new Shape(['y', 'x']);
const ic = makeLoadIC('x');
for (let i = 0; i < 1000; i++) {
ic.load(makeObject(XY, [i, 0]));
}
console.log(ic.stats); // { hits: 999, misses: 1 }
ic.load(makeObject(YX, [0, 42])); // different shape: miss, cache replaced
ic.load(makeObject(XY, [1, 0])); // miss again: the cache forgot XY
console.log(ic.stats); // { hits: 999, misses: 3 }This model keeps only one entry, so alternating shapes cause a miss every time. Real V8 keeps several entries before it gives up, which is the polymorphic state. The overall structure is the same: a check, a cached answer, and a slow path that refills the cache.
Kinds of Inline Caches
Loads are the most common case, but V8 uses the same caching idea for several operations.
| IC kind | Triggered by | What the cache records |
|---|---|---|
| Load IC | `o.x`, `o["x"]` with a constant key | Map, then offset or constant value or getter |
| Store IC | `o.x = v` | Map, offset, and for new properties the transition target map |
| Keyed load/store IC | `o[k]`, `arr[i]` | Map plus elements kind, or a specific key |
| Global load/store IC | Reading a top-level variable | Property cell of the global object |
| Call feedback | `f()`, `o.m()` | Target function seen at the call site |
| `instanceof` / `in` feedback | `a instanceof B`, `"x" in o` | Map and result |
Store ICs and Transitions
A store that adds a new property changes the object's map. The store IC caches both maps: "an object with map M1 storing z moves to map M2 and writes at offset 16." This is why constructors that always assign the same properties in the same order are cheap. After the first object, every this.x = ... in the constructor hits a cached transition.
Loads From Prototypes
Methods usually live on a prototype, not on the instance. A load like point.toString misses on the instance and finds the property two levels up. V8 caches that too, recording the holder object where the property was found. The cache is only safe while no object on the prototype chain changes in a way that could shadow or remove the property. V8 handles this with a validity cell attached to prototype maps. Changing a prototype invalidates the cell, and every IC that depends on it misses on its next run and does a fresh lookup.
Common Mistakes When Reasoning About ICs
- Assuming the cache is per object. It is per access site. One badly behaved call site does not slow down other sites that read the same property.
- Assuming same keys means same map.
{x, y}and{y, x}have different maps, so they count as two shapes at a site that sees both. - Forgetting that helper functions share sites. A generic
get(obj, key)utility used across the whole codebase sends every shape through the same few ICs. Small, specific functions often stay monomorphic. Shared utilities usually do not. - Over-reading microbenchmarks. A cache miss costs roughly a runtime call, measured in tens of nanoseconds. It matters in loops that run millions of times, and almost never elsewhere.
Exercise
In the toy model, the load IC saw 1000 XY objects and then alternated YX, XY, YX, XY for 100 more calls. How many misses would it record in total, and how would a real V8 load IC behave differently?
Show answer
The toy cache holds one shape, so every alternating call misses: 1 initial miss plus 100 misses, giving 101. V8 would add the second map to the slot and go polymorphic, holding both XY and YX. After the first YX miss, later calls with either shape would hit after a short linear check of the cached maps.
Exercise
Two functions, readA(o) { return o.x; } and readB(o) { return o.x; }, are each called only with objects of a single but different map. Is either property access polymorphic? Why?
Show answer
No. Each o.x is a separate access site with its own feedback slot. readA's slot sees only one map, and so does readB's, so both stay monomorphic even though the program uses two maps overall.
Exercise
Why does a store IC for this.y = y inside a constructor need to remember two maps, while a load IC for o.y needs only one?
Show answer
The store adds a property, so it changes the object's hidden class. The cache must record the map before the store, to check the incoming object, and the map after it, to install on the object, along with the offset to write. A load leaves the object unchanged, so checking the one map and reading the offset is enough.