Languages and runtimesDive 01 of 06
What V8 does with your JavaScript
One distance function, four execution tiers, and an assumption that breaks. Step through real bytecode, build hidden classes, feed an inline cache, and follow a deoptimization down to the machine instructions that caused it.
- Levels
- 9
- Reading
- 43 min
- Depth
- Idea to Machine
- Published
Same JavaScript. Different evidence.
Where is x?
V8 remembers the layouts arriving at p.x. One layout gives it one shortcut. Keep changing the layout and that shortcut stops fitting.
Monomorphic: one Map, one specialized field load.
distance(p, q)p.xone load site- M1xyzx at +24
- M2yxzx at +32
- M3xzyx at +24
- M4yzxx at +40
- M5zxyx at +32
- M6zyxx at +40
Model of the recorded named-load IC: 1 Map, then 2–4, then a megamorphic handler. Offsets match this uncompressed Node build’s additive objects.
Every property access asks a question
You are moving points around a canvas. For every nearby pair, you calculate a distance. The function is five lines long. It reads four fields, subtracts, multiplies and adds. You call it thousands of times per frame, and almost every call sees the same kind of point.
JavaScript gives you a wonderfully small interface to that job. You do not declare the layout of a point, choose an integer width, allocate an output buffer or tell the compiler which implementations are allowed. Here is the entire function we will follow. It returns the squared Euclidean distance, so comparisons can avoid a square root.
function distance(p, q) {
const dx = p.x - q.x;
const dy = p.y - q.y;
return dx * dx + dy * dy;
}= 32 + 42 = 25
Now consider what p.x promises. The caller could hand you an object with x stored directly inside it. Or x could live in a property table, come from a prototype, run a getter, or be intercepted by a Proxy. The value could be a number, a string or something with a conversion method that runs more JavaScript. Each possibility has observable behavior. The engine must preserve it even when the fast case is overwhelmingly more common.
V8’s central trick is to separate the answer the language permits from the answer this particular code usually needs. It starts with machinery that can handle general JavaScript. As the function runs, it collects evidence. If one object layout keeps arriving, a compiler can generate a layout check followed by a fixed-offset load. If arithmetic keeps receiving small integers, it can use integer instructions. The checks are what make those shortcuts correct.
This is Compiling for properties observed during execution, with checks or tracked dependencies that make unexpected cases safe.. The engine is allowed to guess how the next call will behave because it keeps a way to recover when that guess fails. A wrong guess is a performance event, not permission to return the wrong JavaScript value.
There is another constraint: compilation costs time too. An application ships far more functions than one interaction will execute. Spending an expensive optimization pass on every function would delay the first useful frame and retain code that may never run. V8 therefore has several execution tiers, trading compilation effort for the speed of later execution. Our point calculation is a good candidate for climbing them; a rarely opened settings dialog might never need to.
We will change the evidence while leaving the function alone. First, every point has the same layout. Then the same names arrive in different insertion orders. Finally, a multiplication exceeds the integer representation the compiler selected, or a numeric field becomes a string. Those tiny changes expose the path from property names to machine instructions, and the escape hatch back.
V8 makes dynamic JavaScript fast by remembering what happened, compiling for that evidence, and preserving a correct continuation when it changes.
Pay for the code you need
Before an object layout can matter, the engine has to understand the source. A scanner turns characters into tokens. A parser recognizes their grammatical relationships and constructs an abstract syntax tree, or AST. Scope analysis determines which declaration each variable refers to. The bytecode generator then has enough information to describe execution.
The distinction between names is already important. In p.x, p refers to a parameter binding, while x is the name of a property to look up later. Scope resolution can settle where p lives before running the function. It cannot settle the meaning of x for every possible object. That question survives into the bytecode.
const dx = p.x - q.x;const · dx · = · p · . · x · − · q · . · xDeclare dx ← Subtract(Property(p, x), Property(q, x))p: argument a0 · q: argument a1 · dx: register r0- The scanner reads source characters and recognizes identifiers, keywords and punctuation.
- The scanner supplies tokens to the parser. A dot is syntax; “x” is a property name here, not a lexical variable.
- The parser builds an abstract syntax tree. This schematic names its meaning, not V8’s internal AST node spelling.
- Scope analysis resolves p and q to parameters and dx to a local. distance captures no outer variable; these locals need no closure context.
Fully parsing every nested function immediately would create work for code you may never call. V8 can instead preparse a function: validate its syntax and collect enough scope information to compile the surrounding code, while delaying its complete AST and bytecode. A later call can trigger full parsing. Functions needed immediately may be compiled eagerly; an immediately invoked function expression is a useful example. Nesting alone does not make every inner function eager. The V8 preparser article explains the saved scope information and eager heuristics.
Scope information cannot be skipped just because execution is deferred. Imagine a factory that creates a point-specific distance callback. If the callback refers to a local variable in the factory, it may still need that variable after the factory returns. The parser must recognize the capture so the value can live in a heap-allocated context rather than disappear with a stack frame.
function from(origin) {
return function distanceFrom(p) {
return distance(p, origin);
};
}
const fromHome = from({ x: 0, y: 0 });The closure carries a connection to the context containing origin. That is different from saying every variable in every JavaScript function lives in a heap box. Our standalone distance function captures nothing. Its arguments can be addressed as parameters, and its local intermediates can use interpreter registers. Later compilation may eliminate some of those intermediates altogether.
Syntax, bindings and object properties are three different layers. The syntax tells the engine to subtract two property values. Binding resolution finds p and q. Property access still has to inspect their runtime receivers. Keeping those layers separate explains why the next representation contains both very direct local-register operations and more general property-load operations.
Parsing resolves the program’s structure and lexical names. Runtime feedback answers questions about the values those names eventually carry.
Forty-one bytes that can run
Ignition executes compact bytecode rather than walking the AST. It is a register machine with an An implicit working register used as an operand or result by many bytecode instructions.. Instructions can name parameter and local-register slots while leaving a common input or output implicit in the accumulator. That keeps instructions small without requiring an operand stack for every expression.
Our recording contains 41 bytes and 17 instructions. V8 reports three parameters because the implicit receiver counts alongside p and q. It reports three registers: r0, r1 and r2. These are slots in an interpreter frame, not a promise that the x86-64 processor reserves three hardware registers for the source function.
Step once to read p.x into the accumulator. Step again: Star2 copies it into r2. The next property load replaces the accumulator with q.x. Sub r2 subtracts the accumulator from r2 and leaves the difference in the accumulator. Star0 saves that as dx. The y calculation reuses r2; the final expression reuses it again for dx squared.
Node v26.13.0 · V8 14.6.202.34-node.40 · x86-64 · --allow-natives-syntax --input-type=commonjs --print-bytecode --print-bytecode-filter=distance
- 0
GetNamedProperty a0, [0:"x"], FBV[1]33 03 00 01 - 4
Star2d0 - 5
GetNamedProperty a1, [0:"x"], FBV[3]33 04 00 03 - 9
Sub r2, FBV[0]41 f7 00 - 12
Star0d2 - 13
GetNamedProperty a0, [1:"y"], FBV[6]33 03 01 06 - 17
Star2d0 - 18
GetNamedProperty a1, [1:"y"], FBV[8]33 04 01 08 - 22
Sub r2, FBV[5]41 f7 05 - 25
Star1d1 - 26
Ldar r00b f9 - 28
Mul r0, FBV[11]42 f9 0b - 31
Star2d0 - 32
Ldar r10b f8 - 34
Mul r1, FBV[12]42 f8 0c - 37
Add r2, FBV[10]40 f7 0a - 40
Returnb7
After the last executed instruction
- Accumulator
- undefined
- r0 · dx
- undefined
- r1 · dy
- undefined
- r2 · temporary
- undefined
a0 = p · a1 = q
Byte offsets are decimal; byte encodings are hex. Registers begin as undefined.
Ready: 0 / 17 instructions. The accumulator and three registers start undefined.
Inputs are finite numeric own fields, ±100000. The model executes the captured 17-instruction sequence; native JavaScript checks the final answer.
The displayed bytes are real instruction encodings from the capture, including compact Star0, Star1 and Star2 forms. The viewer executes their numeric-field subset. Its inputs are ordinary own numeric properties, so it needs neither a getter evaluator nor a prototype-chain simulator. Changing a coordinate immediately discards the previous frame history. You can then step to return and compare the result with the same arithmetic executed by the browser.
Notice the two coordinate systems in the listing. Offset 13 means the fourteenth byte of the bytecode array. FBV[6] means feedback-vector slot 6. Neither means “line 6” of your source. A bytecode instruction may occupy several bytes, and a feedback entry may occupy several slots. The slots allocated for property loads are interleaved with slots for arithmetic.
The constant pool holds the property-name strings x and y. Four different loads can refer to those same two names while maintaining separate runtime feedback. That separation is essential: the p receiver might vary among many layouts while q remains the same origin object. Sharing the spelling “x” does not merge their observation histories.
| Expression | Byte offset | Feedback entry starts at |
|---|---|---|
| p.x | 0 | 1 |
| q.x | 5 | 3 |
| p.y | 13 | 6 |
| q.y | 18 | 8 |
Feedback is attached to executable operations, not to the source text as a whole. A property-load entry can remember a receiver Map and a handler that knows how to access the field. An arithmetic entry can summarize observed operand categories. A compiler reads those observations when deciding whether it is worthwhile to replace a general operation with a narrower one.
The accumulator also explains some apparent extra movement. To square dx, the bytecode loads r0 into the accumulator, then multiplies r0 by it. To add both squares, it saves one in r2 and computes the other in the accumulator. A later optimizer can see the data dependencies directly and avoid treating every bytecode movement as an obligatory machine instruction.
Do not confuse this bytecode with a portable format shipped over the web. JavaScript source is the language interface. Ignition bytecode is an implementation detail that can change across V8 versions. The WebAssembly stack machine has a different job: its module format is a specified input to multiple engines. Here, V8 owns both the producer and consumer of the bytecode, so it can change the encoding together with its interpreter and compilers.
Bytecode is more than a cheap starting point. It becomes a stable vocabulary for unoptimized execution: source positions, register slots and instruction offsets give the optimizing tiers something concrete to recover to. We will need exactly those coordinates when a machine-code guard eventually fails.
Give changing objects a stable shape
A fast property load needs a compact answer to “where is x in this object?” V8 gives ordinary objects a V8’s internal metadata object describing an object’s layout, property descriptors, prototype and other structural facts; often called a hidden class.. This is V8’s internal capital-M Map, not JavaScript’s Map collection. Many objects can point to the same Map, allowing one identity check to establish shared layout facts.
Start with an empty object. Add x, then y. The object moves through a sequence of Maps. A second object created along the same path can reuse the same transitions. Their field values may differ; their property structure can still match. Add y before x and you take a different path, even though both final objects expose the same property names.
Build two objects below. Give A the sequence x, y, z and B the sequence y, x, z. Then reset and give them the same sequence. The tree marks the paths you actually took. Each label stands for a Map in this restricted additive construction pattern, verified against %HaveSameMap in the measured V8 build.
{}Map ∅{}Map ∅A and B share Map ∅.
Choose A or B, then add properties in an order. Equal values are not required to share a Map.
Validated subset: ordinary objects created with {}, the same prototype, and distinct x/y/z fields holding Smis. No accessors, attributes, deletion or representation changes.
A Map’s descriptors connect property names to metadata such as attributes, field indices and representations. A field index can refer to a slot inside the object itself, an in-object property, or to storage reached through its properties pointer. Keeping common fields inside the object saves a dependent load and puts related values close together in memory.
Objects have limited in-object capacity. Growing beyond it does not automatically mean dictionary mode: fast properties can use a separate backing array while descriptors still describe the layout. In our additive-object recording, four slots fit in the 56-byte instance. Adding eight named properties leaves four in-object and uses a PropertyArray for the remaining fields. “Outside the object” and “dictionary lookup” are different conditions.
Constructor-created objects can also change their reserved in-object capacity during warmup. V8’s slack tracking learns how much room that constructor’s objects need; the before-and-after Point capture below shows an existing object shrinking. The additive builder here holds its construction pattern fixed.
A single generic source function can therefore see several layouts. One application constructs points as x then y. Another deserializes fields in a different order. A third attaches a debugging field before coordinates. All are legal points from JavaScript’s perspective. The optimization question is whether a particular load site keeps seeing enough regularity to profit from specialized access.
Property order is only one ingredient. Prototypes, property attributes, allocation patterns and field representations can also affect Maps and their evolution. Two object literals that look similar need not share the same transition history as two initially empty objects extended by the same assignments. The builder holds those other variables fixed so the insertion-order effect is visible.
Arrays add a second axis. Named properties and integer-indexed elements have separate storage paths. The fast-properties explanation distinguishes in-object fields, fast backing storage and dictionaries. Array elements carry an elements kind describing both their value representation and whether indexed holes may be present.
A packed Smi array can store small integers. Introducing a fractional number can widen it to packed doubles. Introducing a string requires general tagged elements. Delete an index and the corresponding kind becomes holey: a read may have to account for an absent own property and consult the prototype chain. A hole is not the same as an own element whose value is undefined.
Named fields have Maps; array indices also have elements kinds.
PACKED_SMI_ELEMENTS
[1, 2, 3] starts packed with small integers. Try widening it, then writing an integer back.
Push/delete/overwrite subset, capped at 8 slots. Array.prototype.fill has a repacking exception added in 2025; this widget does not use fill.
These six common kinds form a lattice: value representations widen from Smi to double to tagged, and packed kinds can become holey. Ordinary overwrites do not simply walk backwards when you put an integer back. That makes accumulated representation history matter. The elements-kinds article now records an exception added in February 2025: Array.prototype.fill can repack eligible arrays. The experiment uses push, delete and single-element overwrite, so its transitions stay within the captured subset.
This is why “JavaScript arrays are contiguous doubles” is not a useful general model. Some are contiguous double storage; some contain tagged values; some have holes or dictionary elements. Typed arrays offer a more explicit element representation when your application needs one. Ordinary point objects offer flexibility, and V8 recovers structure from how you actually build and use them.
The practical lesson is to make natural data regular where you can. A constructor that always initializes x and y in one order gives the engine consistent evidence. That is useful when it follows the application’s meaning. Inventing a maze of constructors to game one microbenchmark usually adds complexity faster than it saves time.
Changing a prototype changes the lookup
A field descriptor is useful only in the lookup context it describes. If an object lacks an own x, JavaScript searches its prototype chain. A getter there can compute a value or mutate other objects. A Proxy can intercept the operation altogether. A handler for such an access needs different checks and dependencies from a direct in-object field load.
That is why “same keys” is weaker than “same Map.” A key list omits the prototype, attributes and representation facts that make a handler valid. It also explains why mutating a widely used prototype can affect code far away from the assignment: compiled code may depend on the absence of a property or on a particular prototype-chain relationship. V8 has to invalidate or recheck those facts when they change.
The point builder excludes these operations so you can isolate one cause. In production, keep the distinction in mind when a trace reports a wrong Map for objects that appear identical in a log. A JSON rendering shows enumerable values. It does not show all of the structural facts the engine was relying on.
Objects share layout metadata. The Map turns a question about a property name into a checkable fact about a field position.
Remember what this load has seen
The Map describes an object. An A property-access mechanism that remembers receiver layouts and their access handlers at one executable operation., or IC, describes the history of a particular access site. For our experiment, that site is p.x at bytecode offset 0. Its job is to reuse a previously established route to the property instead of repeating the full lookup every time.
Before the first observed receiver, the entry is uninitialized. One receiver Map makes it monomorphic. The entry can associate that Map with an access handler. If a later receiver has the same Map, the engine can use the known handler. The point need not be the same object; thousands of distinct point objects can take the same monomorphic path.
A second supported Map makes the entry polymorphic. It now represents several specialized cases. In our build, the flag --max-valid-polymorphic-map-count defaults to 4. The fifth distinct stable receiver Map pushes this named-load site into the megamorphic state. The V8 flag definition and, more directly, our recorded feedback vector establish that limit for this experiment.
Only p.x · GetNamedProperty at bytecode offset 0 · feedback slot 1
First load will install a specialized handler.
No receiver yet. Feed the same Map twice, then introduce four others.
Recorded V8 feedback · canonical M1, M2, … sequence with this many distinct Maps
- slot #1 LoadProperty UNINITIALIZED {
[1]: 0x0a2eaca41991 <Symbol: (uninitialized_symbol)>
[2]: 0x0a2eaca41991 <Symbol: (uninitialized_symbol)>
}Stable fast-property receiver Maps, capped at 4 by this build’s --max-valid-polymorphic-map-count=4. Recorded snapshots use canonical order; the model above uses your order.
Feed M1 several times before feeding M2. Repetition does not make a site polymorphic; diversity does. Next feed M3 and M4, then M5. The bounded local list gives way to a more general handler. A subsequent M1 does not reset the accumulated history. Resetting the experiment explicitly creates fresh model feedback.
The widget’s six objects contain x, y and z, inserted in all six possible orders. z is an otherwise unused field that lets us create more than two layouts while keeping the mathematical inputs unchanged. Just swapping x and y gives only two orderings, which cannot by itself demonstrate a five-Map transition. The same distance source still reads only x and y.
Megamorphic does not mean “do a completely uncached dictionary search every time.” Named-load machinery can consult a shared stub cache keyed by facts such as receiver Map and property name. It can reuse a handler even after this particular feedback entry has stopped carrying a short list. A cache miss can go through more general lookup and install useful information for later accesses.
Nor does polymorphic automatically mean slow. A compiler may generate a small dispatch among several layouts, reuse a common load when offsets agree, or decide the specialization is not worthwhile. More cases can increase checks and code size, but the result depends on the actual handlers, surrounding code and workload. The useful distinction is how much local, specific evidence remains available to the optimizer.
Our q.x site stays separate. q remains a plain origin object while p cycles through six layouts. That gives one function both a megamorphic p load and a monomorphic q load. The four property loads in the bytecode are four optimization opportunities, each with its own evidence. Thinking of the whole function as “having one shape” hides that structure.
Feedback is a sample of execution so far, not a proof of every future call. A stable month of requests cannot prove that the next one will avoid a different prototype or a numeric string. The compiler must guard observations that can vary, or register dependencies whose changes invalidate the generated code. This is where caching and optimization connect: caches make current execution cheaper, and their accumulated information gives later compilation a narrower problem.
Feedback belongs to a context of execution
Moving an operation into a shared helper can bring together callers that used to have separate observation histories. Suppose two canvas layers each process one regular point representation. A helper that handles both may see two Maps at its p.x load. Conversely, duplicating code just to isolate feedback can increase code size and maintenance cost. The effect is worth investigating when a profile points there; it is not a universal argument against helpers.
The feedback vector also does not retain every concrete receiver forever. V8 uses weak references for relevant Map entries so observation alone need not keep an otherwise dead layout alive indefinitely. Cleared or deprecated Maps, migration and handler updates make real IC behavior richer than a permanent set of all shapes ever seen. The widget fixes six live stable Maps, which makes its state sequence reproducible without pretending to model garbage collection.
Spend compilation where it pays
So far the engine has code that can execute and feedback about how it executes. The next decision is economic: how much compilation effort should it spend? Startup wants a quick first result. A hot loop wants low cost per iteration. Several tiers let V8 improve execution without charging every function the full price of its most ambitious compiler.
Ignition runs bytecode with reusable interpreter handlers. Sparkplug compiles bytecode into baseline machine code, removing interpreter decoding and dispatch without building a heavyweight optimizing IR. Maglev builds a compact, control-flow-based SSA graph and specializes operations using feedback. TurboFan invests more in optimization for code that remains hot. They are execution tiers, not four transformations every function must obligatorily visit.
| Tier | What it executes | Where effort goes |
|---|---|---|
| Ignition | Bytecode, interpreted | Compact initial representation and general handlers |
| Sparkplug | Baseline native code | Fast translation; avoid repeated interpreter dispatch |
| Maglev | Optimized native code | Quick SSA construction, feedback specialization, limited passes |
| TurboFan | Top-tier native code | More optimization work; Turboshaft-based JavaScript backend |
Sparkplug’s design starts from work the bytecode generator already completed: resolved variables, lowered syntax and known control flow. It can translate that representation quickly and maintain interpreter-compatible frames. It is a baseline compiler: producing native code does not require discovering an optimal global arrangement of the computation.
Maglev makes the dataflow more explicit. In static single assignment, each graph value has one definition. A source variable reassigned in a loop can correspond to several graph values, with merge nodes selecting the appropriate incoming value. The graph also tracks enough abstract interpreter state to describe how an optimized computation corresponds to bytecode registers.
For distance, this makes a useful distinction visible: the compiler can know a graph value holds an integer even though JavaScript itself never declared an integer variable. It can place guards at the boundaries where the assumption needs checking, then use specialized operations internally. That is a local implementation choice justified by the observed calls.
TurboFan can invest further in inlining, redundant-check elimination and escape analysis. Inlining brings a callee’s computation into its caller’s graph. Escape analysis may show that a temporary object never needs an independently observable identity, allowing its fields to remain as values rather than a materialized heap allocation. These are opportunities, not guarantees for every point or callback.
Historically, TurboFan used a Sea of Nodes representation that mixed data and control dependencies in a flexible graph. The 2025 migration report says its JavaScript backend had moved to Turboshaft, a more explicit control-flow-graph IR, while some frontend and builtin work still used Sea of Nodes. Our local flags also expose Turbolev, combining a Maglev frontend with Turboshaft as a possible fourth-tier pipeline; that flag is disabled by default here. “TurboFan” names the top-tier compiler role in these recordings, not a claim that its entire implementation still uses the original graph.
[marking 0x388054b052f1 <JSFunction distance (sfi = 0x388054b00da1)> for optimization to MAGLEV, ConcurrencyMode::kConcurrent, reason: hot and stable]
[compiling method 0x388054b052f1 <JSFunction distance (sfi = 0x388054b00da1)> (target MAGLEV), mode: ConcurrencyMode::kConcurrent]
[completed compiling 0x388054b052f1 <JSFunction distance (sfi = 0x388054b00da1)> (target MAGLEV) - took 0.001, 1.791, 0.014 ms]
[compiling method 0x388054b05259 <JSFunction (sfi = 0x388054b00ce9)> (target TURBOFAN_JS) OSR, mode: ConcurrencyMode::kConcurrent]
[completed compiling 0x388054b05259 <JSFunction (sfi = 0x388054b00ce9)> (target TURBOFAN_JS) OSR - took 0.030, 8.836, 0.066 ms]
[completed optimizing 0x388054b05259 <JSFunction (sfi = 0x388054b00ce9)> (target TURBOFAN_JS) OSR]
checksum 28500000This is a separate natural-tiering run: a million calls in a hot loop, no optimization-forcing intrinsic. This capture records distance reaching Maglev; the enclosing loop reaches TurboFan through OSR. Tier timing varies between runs. The checksum keeps the result observable. Timing fields describe this run’s compilation, including concurrent work; they are not a startup promise or the time needed to execute a call.
The surrounding loop also demonstrates On-stack replacement: transferring a currently running activation into compiled code at a supported point, often a loop backedge.. Waiting until the next function call would be useless if a single activation spends seconds inside a loop. At supported points, V8 can transfer that running activation to compiled code. It must map the existing values into the new frame arrangement, rather than start the function again and repeat its effects.
Budgets, bytecode size, backedges, feedback stability, compiler availability and prior deoptimizations all influence tiering. A literal “optimize after N calls” rule will mislead you across versions and even across functions in one version. If an optimization does not pay for its compilation before the work ends, an earlier tier may have been the better choice. If feedback changes, another compilation may produce a better plan later.
Compilation is work on the same machine
Concurrent compilation can move a substantial part of optimization away from the JavaScript execution thread. It still consumes CPU, memory bandwidth and compiler memory, and publishing generated code still needs coordination. A trace saying “concurrent” should not be read as “free.” On a busy machine, the application and compiler can contend for resources even while their tasks run on different threads.
Code size is another cost. An inlined distance calculation can save call overhead and expose arithmetic to the caller’s optimizer. Repeating that expansion at many sites also produces more instructions for caches to hold. Tier policy and inlining budgets balance these effects. The engine’s job is to improve the whole execution, including the functions that finish before peak speed could ever repay a long compilation.
Tiering trades compilation cost now for cheaper execution later. The most optimized tier wins only when enough useful work remains.
An assumption breaks; JavaScript continues
Now break a compiler assumption. Train distance with small integer coordinates, compile it, and then set p.x to 50000. JavaScript still requires the numerical result 2500000016. The mathematical multiplication is perfectly ordinary, but its intermediate value 2500000000 exceeds the signed 32-bit representation chosen by the optimized integer path.
A guard detects the mismatch. V8 leaves the optimized path and reconstructs an unoptimized continuation. That transfer is Reconstructing a less specialized execution state when optimized code can no longer safely continue under its assumptions.. The engine must preserve JavaScript semantics: values, control position, completed side effects and the behavior still to come.
The explorer contains three real recordings from separate processes. Choose overflow, a differently ordered point, or a field becoming a string. Each shows the event V8 actually reported. The warmup and %OptimizeFunctionOnNextCall make these small demonstrations reproducible; they deliberately control the moment of top-tier compilation.
p.x = 50000; distance(p, q)Int32 dx = 50000; dx × dx needs 2500000000.
Resume unoptimized execution at offset 0; JavaScript returns 2500000016.
Eager bailout · reason: overflow · bytecode offset 0
The inputs still fit this build’s 32-bit Smi range. The speculative Int32 product does not fit signed 32 bits. The checkpoint in this capture is at the start of the function.
Node v26.13.0 · V8 14.6.202.34-node.40 · x86-64 · --allow-natives-syntax --input-type=commonjs --trace-opt --trace-deopt --print-opt-code --print-opt-code-filter=distance
[manually marking 0x0112cba85221 <JSFunction distance (sfi = 0x112cba80cd1)> for optimization to TURBOFAN_JS, ConcurrencyMode::kSynchronous]
[compiling method 0x0112cba85221 <JSFunction distance (sfi = 0x112cba80cd1)> (target TURBOFAN_JS), mode: ConcurrencyMode::kSynchronous]
[completed compiling 0x0112cba85221 <JSFunction distance (sfi = 0x112cba80cd1)> (target TURBOFAN_JS) - took 0.028, 1.770, 80.546 ms]
optimized result 32
trigger overflow
[bailout (kind: deopt-eager, reason: overflow): begin. deoptimizing 0x0112cba85221 <JSFunction distance (sfi = 0x112cba80cd1)>, 0x0f8220b08c69 <Code TURBOFAN_JS>, opt id 0, bytecode offset 0, deopt exit 6, FP to SP delta 32, caller SP 0x7ffcd14ef140, pc 0x7f4a9f00746b]
result 2500000016Selected complete trace lines. Each scenario ran in a fresh process. %OptimizeFunctionOnNextCall forces top-tier compilation; these are not natural warmup thresholds.
An eager deopt happens when an explicit runtime check fails in optimized execution. In the overflow capture, the reason is overflow. In the reordered-object capture, it is wrong map. Both recordings report bytecode offset 0 as the continuation checkpoint. Although the overflow is discovered during arithmetic, this compiler arrangement reconstructs a state that resumes at the function’s start. The diagnostic bytecode offset matters more than guessing a source line from the reason string.
How can restarting this particular computation be safe? Up to its chosen checkpoint the compiler has arranged the relevant effects and values so that the continuation preserves behavior. Our trained path contains plain field reads and arithmetic. In a function with calls or stores, V8 must account for their effects and choose corresponding frame states; it cannot blindly rerun an arbitrary getter or send a request twice.
Optimization usually scrambles the apparent source-level state. One source local might be unboxed in a machine register, another might be recoverable from a constant, and an inlined function may have no separate physical stack frame. Deoptimization metadata describes how to translate that state into the logical frames and register values needed by unoptimized code. It can also materialize values or objects that optimization avoided storing in their original form.
Unboxed values; functions may be inlined.
Recover bytecode position, arguments and live values.
Restore the accumulator and registers needed to continue.
- A failed guard reaches a deopt exit. Machine state is specialized; source locals need not occupy their original frame slots.
- The deoptimizer reads translation metadata associated with that exit. Inlined calls can become multiple logical frames.
- Resume general execution. This overflow capture restarts distance at bytecode offset 0.
A lazy deopt is different: code can be invalidated while execution is elsewhere, such as inside a call, and the active frame can be converted when control returns. The string experiment does not demonstrate that event. Its assignment changes a field representation and the trace marks dependent compiled code for deoptimization before the next distance call. There is no active distance frame whose lazy bailout is recorded.
That distinction is useful when reading logs. Code invalidation, an active-frame bailout and later recompilation are related mechanisms, but they are not interchangeable names for one line of output. In the string case, the next call runs without the invalid assumptions. Subtracting the nonnumeric string “three” produces NaN, which propagates through the squares and sum.
An overflowing optimized integer is also different from a JavaScript integer wrapping. JavaScript Number arithmetic uses binary64 semantics. A compiler may use Int32 operations internally if it can detect when their result would no longer match those semantics. The deopt exists so 50000 squared can become the correct larger Number rather than a wrapped negative value. The guard protects the language contract from the chosen representation.
Deoptimization need not permanently condemn a function to interpretation. Broader feedback can lead to new optimized code that handles doubles or several Maps. Repeated unstable behavior can make aggressive speculation unattractive, so the engine may back off. A single bailout may be a sensible cost; a loop that repeatedly generates and invalidates expensive code can be a performance problem.
Deoptimization throws away an unsafe compiled plan. It does not mean the engine discards your objects, your source or the valid work already performed. Recovery is part of the optimization design. A compiler that makes a bold assumption without a faithful continuation has not optimized JavaScript; it has changed the program.
The heap beneath the shapes
A Map check and a field load eventually read memory. To understand their offsets, look at the point’s actual heap representation. The following object was created as an empty object and then extended with x and y. Its debug dump reports 56 bytes, four in-object property slots, and two unused fields. The useful coordinates occupy only part of the allocation.
The header contains a Map reference, a properties-or-hash word and an elements reference. Here the property and element backing stores are empty, because x and y fit inside the object and there are no indexed elements. The Map points to shared metadata rather than copying a table of property names into every point. V8 can therefore check one shared identity and load a field at an established offset.
const p = {}; p.x = 3; p.y = 4;7 × 8 bytes = 56 bytes · offsets from the untagged object address · this allocation path
DebugPrint: 0x125437c27ff1: [JS_OBJECT_TYPE]
- map: 0x2a903b26fdf1 <Map[56](HOLEY_ELEMENTS)> [FastProperties]
- prototype: 0x2e081788a861 <Object map = 0x10447dabb091>
- elements: 0x19b945ac0dd1 <FixedArray[0]> [HOLEY_ELEMENTS]
- properties: 0x19b945ac0dd1 <FixedArray[0]>
- All own properties (excluding elements): {
0x19b945ac5819: [String] in ReadOnlySpace: #x: 3 (const data field 0, attrs: [WEC]) @ Any, location: in-object
0x19b945ac5831: [String] in ReadOnlySpace: #y: 4 (const data field 1, attrs: [WEC]) @ Any, location: in-object
}
0x2a903b26fdf1: [Map] in OldSpace
- map: 0x10447daba5c9 <MetaMap (0x10447daba659 <NativeContext[306]>)>
- type: JS_OBJECT_TYPE
- instance size: 56
- inobject properties: 4
- unused property fields: 2
- elements kind: HOLEY_ELEMENTS
- enum length: invalid
- stable_map
- back pointer: 0x2a903b26fa59 <Map[56](HOLEY_ELEMENTS)>
- prototype_validity_cell: 0x2ba1cdf073b9 <Cell value= [weak] 0x10447daba659 <NativeContext[306]>>
- instance descriptors (own) #2: 0x125437c2afa1 <DescriptorArray[2]>
- prototype: 0x2e081788a861 <Object map = 0x10447dabb091>
- constructor: 0x2ba1cdf3fb31 <JSFunction Object (sfi = 0x3ec5e8ac82e1)>
- dependent code: 0x19b945ac0df1 <Other heap object (WEAK_ARRAY_LIST_TYPE)>
- construction counter: 0A constructor’s spare capacity can shrink
A new constructor starts with a generous in-object allocation. V8’s in-object slack tracking uses early constructions to learn how much space its objects need, then trims unused slots across its transition tree. This can reduce the recorded size of objects already created by that constructor.
Our two-field Point initially reports 104 bytes: three header words and ten in-object slots, eight unused. After 20 more constructions, the same original object reports 40 bytes, two slots and no unused fields. Its x and y values remain 3 and 4. This is constructor slack tracking; the additive object above follows a different allocation path and retains its two spare slots in that recording. Twenty is our observation point, not a universal completion threshold.
Same original Point · before and after constructor warmup
| Recorded property | First construction | 20 more constructions |
|---|---|---|
| Instance size (bytes) | 104 | 40 |
| In-object slots | 10 | 2 |
| Unused slots | 8 | 0 |
Node v26.13.0 · V8 14.6.202.34-node.40 · x86-64 · --allow-natives-syntax --input-type=commonjs
console.log(`Node ${process.version} | V8 ${process.versions.v8} | ${process.arch}`);
function Point(x, y) {
this.x = x;
this.y = y;
}
const original = new Point(3, 4);
console.log("Original point after first construction");
%DebugPrint(original);
for (let i = 0; i < 20; i++) new Point(i, i + 1);
console.log("Same original point after 20 more constructions");
%DebugPrint(original);
Command: node --allow-natives-syntax --input-type=commonjs - < src/dives/v8/slack.cjs.txt
Node v26.13.0 | V8 14.6.202.34-node.40 | x64
Original point after first construction
DebugPrint: 0x31d27b7a7771: [JS_OBJECT_TYPE]
- map: 0x0ecaaecee229 <Map[104](HOLEY_ELEMENTS)> [FastProperties]
- prototype: 0x31d27b7a7699 <Object map = 0xecaaecee189>
- elements: 0x01530a180dd1 <FixedArray[0]> [HOLEY_ELEMENTS]
- properties: 0x01530a180dd1 <FixedArray[0]>
- All own properties (excluding elements): {
0x1530a185819: [String] in ReadOnlySpace: #x: 3 (const data field 0, attrs: [WEC]) @ Any, location: in-object
0x1530a185831: [String] in ReadOnlySpace: #y: 4 (const data field 1, attrs: [WEC]) @ Any, location: in-object
}
0xecaaecee229: [Map] in OldSpace
- map: 0x0537a5cba5c9 <MetaMap (0x0537a5cba659 <NativeContext[306]>)>
- type: JS_OBJECT_TYPE
- instance size: 104
- inobject properties: 10
- unused property fields: 8
- elements kind: HOLEY_ELEMENTS
- enum length: invalid
- stable_map
- back pointer: 0x0ecaaecee1d1 <Map[104](HOLEY_ELEMENTS)>
- prototype_validity_cell: 0x0ecaaecee219 <Cell value= [weak] 0x0537a5cba659 <NativeContext[306]>>
- instance descriptors (own) #2: 0x31d27b7a7861 <DescriptorArray[2]>
- prototype: 0x31d27b7a7699 <Object map = 0xecaaecee189>
- constructor: 0x0ecaaececcc9 <JSFunction Point (sfi = 0xecaaece9d79)>
- dependent code: 0x01530a180df1 <Other heap object (WEAK_ARRAY_LIST_TYPE)>
- construction counter: 6
Same original point after 20 more constructions
DebugPrint: 0x31d27b7a7771: [JS_OBJECT_TYPE]
- map: 0x0ecaaecee229 <Map[40](HOLEY_ELEMENTS)> [FastProperties]
- prototype: 0x31d27b7a7699 <Object map = 0xecaaecee189>
- elements: 0x01530a180dd1 <FixedArray[0]> [HOLEY_ELEMENTS]
- properties: 0x01530a180dd1 <FixedArray[0]>
- All own properties (excluding elements): {
0x1530a185819: [String] in ReadOnlySpace: #x: 3 (const data field 0, attrs: [WEC]) @ Any, location: in-object
0x1530a185831: [String] in ReadOnlySpace: #y: 4 (const data field 1, attrs: [WEC]) @ Any, location: in-object
}
0xecaaecee229: [Map] in OldSpace
- map: 0x0537a5cba5c9 <MetaMap (0x0537a5cba659 <NativeContext[306]>)>
- type: JS_OBJECT_TYPE
- instance size: 40
- inobject properties: 2
- unused property fields: 0
- elements kind: HOLEY_ELEMENTS
- enum length: invalid
- stable_map
- back pointer: 0x0ecaaecee1d1 <Map[40](HOLEY_ELEMENTS)>
- prototype_validity_cell: 0x0ecaaecee219 <Cell value= [weak] 0x0537a5cba659 <NativeContext[306]>>
- instance descriptors (own) #2: 0x31d27b7a7861 <DescriptorArray[2]>
- prototype: 0x31d27b7a7699 <Object map = 0xecaaecee189>
- constructor: 0x0ecaaececcc9 <JSFunction Point (sfi = 0xecaaece9d79)>
- dependent code: 0x01530a180df1 <Other heap object (WEAK_ARRAY_LIST_TYPE)>
- construction counter: 0
Both dumps inspect the original object. Its address and Map identity match in this run; the Map’s instance size, capacity and construction counter change.
This is a concrete allocation path, not a universal point ABI. Our optimized-distance recording uses two-field object literals whose Map reports a 40-byte instance: the same three eight-byte header words plus two fields, without those spare slots. Constructors, literals and dynamic addition can reserve different capacity. Two source-level “points” can expose the same interface while occupying different heap layouts.
V8 often represents general JavaScript values using tagged values. A small integer, or Smi, can fit directly in a tagged word. A reference to a heap object carries a tag distinguishing it from that immediate integer. Heap numbers provide Number values that do not fit the immediate representation. Optimized code may temporarily use unboxed integers or floating-point registers rather than the general tagged form.
The bit details depend on the build. With pointer compression on a 64-bit architecture, tagged heap fields can use 32-bit compressed values, and a Smi has a signed 31-bit payload. That gives the range −230 through 230−1. On our uncompressed x64 Node build, Smis have a signed 32-bit payload, from −231 through 231−1, stored in the upper half of a 64-bit tagged word.
| Representation fact | Pointer-compressed 64-bit V8 | Measured Node x64 build |
|---|---|---|
| Pointer compression | Enabled | Disabled: build variable = 0 |
| Tagged heap field | 4 bytes | 8 bytes |
| Smi payload | 31 signed bits | 32 signed bits |
| Smi low tag bit | 0 | 0; payload is in high 32 bits |
| Heap reference low bit | 1 | 1 |
| Heap address scheme | Offsets within a 4 GiB cage | Full-width references here |
Pointer compression places relevant heap objects within a 4 GiB virtual-address range and stores offsets relative to a base. Reconstructing a full pointer adds the appropriate base. Reserving that range does not mean eagerly committing 4 GiB of physical memory. This address-space arrangement is also distinct from the larger security sandbox described in newer V8 work.
Now revisit overflow. The coordinate 50000 fits either Smi payload width. What breaks is the compiler’s signed Int32 multiplication: 2500000000 exceeds 231−1. A heap-number or unboxed double representation can carry the value, but reaching that representation safely requires honoring the optimized code’s checks and recovery path. Smi range, field representation and arithmetic representation are related choices, not one universal “JavaScript integer size.”
These objects also participate in garbage collection. V8’s Orinoco work includes generational collection and parallel, incremental and concurrent techniques. Short-lived objects can die young; survivors and longer-lived metadata require tracing too. Moving collection can update references, and write barriers help maintain the collector’s invariants as the mutator changes the heap. The Orinoco overview describes those responsibilities.
Compare this with Go’s concurrent marking. Both runtimes need a correct account of reachable objects while application code mutates references, but their heap organization, movement policies and allocation models differ. A JavaScript Map is layout metadata, not a Go type descriptor with identical lifetime and layout rules. The useful comparison is the question each runtime must answer: which references exist, and which objects remain reachable?
At this layer the performance story includes more than instructions per property access. A Map lookup, backing-store load or heap-number allocation can affect cache behavior and collection work. Escape analysis can remove some allocations; regular layouts can simplify access; packed numeric storage can improve locality. Measure the actual workload before exchanging application clarity for a speculative saving in one of those costs.
JavaScript values have a flexible language meaning and concrete, build-specific storage. Fast code depends on translating between those two without losing information.
A property name becomes an offset
We can finally read the shortcut the engine bought. The optimized distance below is real x86-64 output from the same warmup used in the overflow recording. Its instructions occupy 316 bytes in this capture, including guard paths, runtime support and deopt entries. A five-line source function has become a much more explicit agreement with the hardware.
Follow the Map comparison first. The machine loads a tagged receiver, checks that it is a heap object, and compares the receiver’s Map with an expected Map. A conditional branch leaves for a deopt entry if they differ. On the accepted path, loading x needs only a fixed displacement from the receiver. The property name has disappeared from that fast load.
At +0x30, compare p’s Map with the expected Map in rcx. At +0x34, jnz branches to the wrong-map deopt entry. A tagged object pointer is one byte past the aligned address, hence [rdx−1].
0x7f4a9f007340 0 55 push rbp0x7f4a9f007341 1 4889e5 REX.W movq rbp,rsp0x7f4a9f007344 4 56 push rsi0x7f4a9f007345 5 57 push rdi0x7f4a9f007346 6 50 push rax0x7f4a9f007347 7 4883ec08 REX.W subq rsp,0x80x7f4a9f00734b b 488975e0 REX.W movq [rbp-0x20],rsi0x7f4a9f00734f f 493b65a0 REX.W cmpq rsp,[r13-0x60] (external value (StackGuard::address_of_jslimit()))0x7f4a9f007353 13 0f86c7000000 jna 0x7f4a9f007420 <+0xe0>0x7f4a9f007359 19 488b5518 REX.W movq rdx,[rbp+0x18]0x7f4a9f00735d 1d f6c201 testb rdx,0x10x7f4a9f007360 20 0f84e9000000 jz 0x7f4a9f00744f <+0x10f>0x7f4a9f007366 26 48b9c965a8cb12010000 REX.W movq rcx,0x112cba865c9 ;; object: 0x0112cba865c9 <Map[40](HOLEY_ELEMENTS)>0x7f4a9f007370 30 48394aff REX.W cmpq [rdx-0x1],rcx0x7f4a9f007374 34 0f85d9000000 jnz 0x7f4a9f007453 <+0x113>0x7f4a9f00737a 3a 488b7a17 REX.W movq rdi,[rdx+0x17]0x7f4a9f00737e 3e 4c8b4520 REX.W movq r8,[rbp+0x20]0x7f4a9f007382 42 41f6c001 testb r8,0x10x7f4a9f007386 46 0f84cb000000 jz 0x7f4a9f007457 <+0x117>0x7f4a9f00738c 4c 493948ff REX.W cmpq [r8-0x1],rcx0x7f4a9f007390 50 0f85c5000000 jnz 0x7f4a9f00745b <+0x11b>0x7f4a9f007396 56 498b4817 REX.W movq rcx,[r8+0x17]0x7f4a9f00739a 5a 48c1f920 REX.W sarq rcx,320x7f4a9f00739e 5e 8bc9 movl rcx,rcx0x7f4a9f0073a0 60 48c1ff20 REX.W sarq rdi,320x7f4a9f0073a4 64 8bff movl rdi,rdi0x7f4a9f0073a6 66 2bf9 subl rdi,rcx0x7f4a9f0073a8 68 0f80b1000000 jo 0x7f4a9f00745f <+0x11f>0x7f4a9f0073ae 6e 488b4a1f REX.W movq rcx,[rdx+0x1f]0x7f4a9f0073b2 72 4d8b481f REX.W movq r9,[r8+0x1f]0x7f4a9f0073b6 76 49c1f920 REX.W sarq r9,320x7f4a9f0073ba 7a 458bc9 movl r9,r90x7f4a9f0073bd 7d 48c1f920 REX.W sarq rcx,320x7f4a9f0073c1 81 8bc9 movl rcx,rcx0x7f4a9f0073c3 83 412bc9 subl rcx,r90x7f4a9f0073c6 86 0f8097000000 jo 0x7f4a9f007463 <+0x123>0x7f4a9f0073cc 8c 4c8bcf REX.W movq r9,rdi0x7f4a9f0073cf 8f 440fafcf imull r9,rdi0x7f4a9f0073d3 93 0f808e000000 jo 0x7f4a9f007467 <+0x127>0x7f4a9f0073d9 99 4585c9 testl r9,r90x7f4a9f0073dc 9c 0f8508000000 jnz 0x7f4a9f0073ea <+0xaa>0x7f4a9f0073e2 a2 85ff testl rdi,rdi0x7f4a9f0073e4 a4 0f8c81000000 jl 0x7f4a9f00746b <+0x12b>0x7f4a9f0073ea aa 488bf9 REX.W movq rdi,rcx0x7f4a9f0073ed ad 0faff9 imull rdi,rcx0x7f4a9f0073f0 b0 0f8079000000 jo 0x7f4a9f00746f <+0x12f>0x7f4a9f0073f6 b6 4103f9 addl rdi,r90x7f4a9f0073f9 b9 0f8074000000 jo 0x7f4a9f007473 <+0x133>0x7f4a9f0073ff bf 48c1e720 REX.W shlq rdi,320x7f4a9f007403 c3 488bc7 REX.W movq rax,rdi0x7f4a9f007406 c6 488b4de8 REX.W movq rcx,[rbp-0x18]0x7f4a9f00740a ca 488be5 REX.W movq rsp,rbp0x7f4a9f00740d cd 5d pop rbp0x7f4a9f00740e ce 4883f903 REX.W cmpq rcx,0x30x7f4a9f007412 d2 7f03 jg 0x7f4a9f007417 <+0xd7>0x7f4a9f007414 d4 c21800 ret 0x180x7f4a9f007417 d7 415a pop r100x7f4a9f007419 d9 488d24cc REX.W leaq rsp,[rsp+rcx*8]0x7f4a9f00741d dd 4152 push r100x7f4a9f00741f df c3 retl0x7f4a9f007420 e0 48ba0000000030000000 REX.W movq rdx,0x30000000000x7f4a9f00742a ea 52 push rdx0x7f4a9f00742b eb 48bba0e43c0100000000 REX.W movq rbx,0x13ce4a00x7f4a9f007435 f5 b801000000 movl rax,0x10x7f4a9f00743a fa 48be59a6830c763e0000 REX.W movq rsi,0x3e760c83a659 ;; object: 0x3e760c83a659 <NativeContext[306]>0x7f4a9f007444 104 e8f775e31f call 0x7f4abee3ea40 (CEntry_Return1_ArgvOnStack_NoBuiltinExit) ;; near builtin entry0x7f4a9f007449 109 e90bffffff jmp 0x7f4a9f007359 <+0x19>0x7f4a9f00744e 10e 90 nop0x7f4a9f00744f 10f 41ff55d8 call [r13-0x28] (external value (IsolateData::builtin_tier0_entry_table_)) ;; debug: deopt position, script offset '29' ;; debug: deopt position, inlining id 'ffffffff' ;; debug: deopt reason 'Smi' ;; debug: deopt index 00x7f4a9f007453 113 41ff55d8 call [r13-0x28] (external value (IsolateData::builtin_tier0_entry_table_)) ;; debug: deopt position, script offset '29' ;; debug: deopt position, inlining id 'ffffffff' ;; debug: deopt reason 'wrong map' ;; debug: deopt index 10x7f4a9f007457 117 41ff55d8 call [r13-0x28] (external value (IsolateData::builtin_tier0_entry_table_)) ;; debug: deopt position, script offset '2f' ;; debug: deopt position, inlining id 'ffffffff' ;; debug: deopt reason 'Smi' ;; debug: deopt index 20x7f4a9f00745b 11b 41ff55d8 call [r13-0x28] (external value (IsolateData::builtin_tier0_entry_table_)) ;; debug: deopt position, script offset '2f' ;; debug: deopt position, inlining id 'ffffffff' ;; debug: deopt reason 'wrong map' ;; debug: deopt index 30x7f4a9f00745f 11f 41ff55d8 call [r13-0x28] (external value (IsolateData::builtin_tier0_entry_table_)) ;; debug: deopt position, script offset '2b' ;; debug: deopt position, inlining id 'ffffffff' ;; debug: deopt reason 'overflow' ;; debug: deopt index 4
Node v26.13.0 · V8 14.6.202.34-node.40 · x86-64 · --allow-natives-syntax --input-type=commonjs --trace-opt --trace-deopt --print-opt-code --print-opt-code-filter=distance - overflow < capture.cjs.txt. First 88 disassembly lines; complete output below.
The displacement is initially surprising: [rdx+0x17] is 23 bytes past the pointer, although the field starts 24 bytes into the object. V8’s tagged heap pointer is one past the aligned object address. Subtracting the tag from the conceptual field address produces the encoded displacement. The Map itself is therefore read at [rdx-0x1].
The integer values in this uncompressed build need another conversion. The captured sequence shifts the tagged coordinates right by 32 bits before performing signed 32-bit subtraction. It multiplies the differences using imull and checks the overflow flag with jo. The final sum is shifted left by 32 to return a Smi on the successful path.
There is no scalar floating-point arithmetic in this integer-specialized recording, and no vectorization of several points at once. On paths specialized for floating-point values, x86-64 engines can use scalar floating-point operations in SIMD registers, such as double-precision subtract, multiply and add. Using an XMM register alone does not establish that a compiler processes several independent distances in parallel. The code shown earns only the claims its instructions demonstrate.
Likewise, the machine is not running one instruction for each bytecode. The optimizer has treated the bytecode as a description of dataflow and observable behavior. It can remove redundant movement, combine facts about receivers and representations, and place checks where they protect later operations. It then emits a machine-specific register and stack arrangement plus the metadata needed to get out of it.
That is the whole descent. The source gives you dynamic objects and Number arithmetic. The scanner and parser establish structure. Ignition provides a compact executable description. Maps turn object structure into shared metadata; ICs remember the structures seen at particular operations. Tiering spends compilation effort on repeated work. Guards and dependencies make speculation reversible. At the bottom, a name like x becomes a displacement and a failed assumption becomes a branch.
When investigating your own code, begin with a profile and a repeatable workload. Find whether the time is really in JavaScript execution, parsing, allocation or somewhere else. Then ask a specific question of the engine: which load sees several Maps, which operation broadens its numeric feedback, which reason repeatedly invalidates compiled code? A trace is most useful when it answers a hypothesis about an observed cost.
The comparison with Zig’s compile-time specialization is revealing: Zig can run chosen computations before the program starts, using values required to be known. V8 specializes using values observed while the program runs, so it carries a recovery obligation. And unlike the ordering contract for atomics, layout speculation does not impose a new obligation on your program: the engine must keep its shortcut faithful to ordinary JavaScript.
What a microbenchmark has to preserve
A useful measurement must keep the intended work alive. If every call returns a value that nothing observes, an optimizer may remove or simplify the computation. If every input is constant, a benchmark may mostly measure a constant-folded result. If object creation happens inside the timed loop, allocation and collection can dominate a comparison intended to isolate property access. Those are different experiments, each useful when named correctly.
The natural-tiering capture varies p.x and accumulates the returned distances into an observable checksum. Its purpose is to show compilation events, not rank the engine against another language. A timing comparison would also need repeated runs, controlled warmup, a distribution of realistic inputs and a clear boundary around what is being timed. Debug flags themselves can affect execution, so diagnostic runs and timing runs should be interpreted separately.
Most importantly, verify that the proposed explanation survives a controlled change. If inconsistent construction order is the hypothesis, keep the algorithm and values fixed while making that order consistent. If the cost remains, look elsewhere. A dramatic assembly listing is evidence of generated code; a profile plus an improved application outcome is evidence that the code mattered.
Reproduce the evidence · Node v26.13.0 · V8 14.6.202.34-node.40 · x86-64
Command: node --allow-natives-syntax --input-type=commonjs --print-bytecode --print-bytecode-filter=distance - bytecode < src/dives/v8/capture.cjs.txt
Node v26.13.0 | V8 14.6.202.34-node.40 | x64
[generated bytecode for function: distance (0x159145eaa089 <SharedFunctionInfo distance>)]
Bytecode length: 41
Parameter count 3
Register count 3
Frame size 24
41 S> 0x31fb5c0888a8 @ 0 : 33 03 00 01 GetNamedProperty a0, [0:"x"], FBV[1]
0x31fb5c0888ac @ 4 : d0 Star2
47 E> 0x31fb5c0888ad @ 5 : 33 04 00 03 GetNamedProperty a1, [0:"x"], FBV[3]
43 E> 0x31fb5c0888b1 @ 9 : 41 f7 00 Sub r2, FBV[0]
0x31fb5c0888b4 @ 12 : d2 Star0
65 S> 0x31fb5c0888b5 @ 13 : 33 03 01 06 GetNamedProperty a0, [1:"y"], FBV[6]
0x31fb5c0888b9 @ 17 : d0 Star2
71 E> 0x31fb5c0888ba @ 18 : 33 04 01 08 GetNamedProperty a1, [1:"y"], FBV[8]
67 E> 0x31fb5c0888be @ 22 : 41 f7 05 Sub r2, FBV[5]
0x31fb5c0888c1 @ 25 : d1 Star1
76 S> 0x31fb5c0888c2 @ 26 : 0b f9 Ldar r0
86 E> 0x31fb5c0888c4 @ 28 : 42 f9 0b Mul r0, FBV[11]
0x31fb5c0888c7 @ 31 : d0 Star2
0x31fb5c0888c8 @ 32 : 0b f8 Ldar r1
96 E> 0x31fb5c0888ca @ 34 : 42 f8 0c Mul r1, FBV[12]
91 E> 0x31fb5c0888cd @ 37 : 40 f7 0a Add r2, FBV[10]
101 S> 0x31fb5c0888d0 @ 40 : b7 Return
Constant pool (size = 2)
0x31fb5c088849: [TrustedFixedArray]
- map: 0x05ca38980ab9 <Map(TRUSTED_FIXED_ARRAY_TYPE)>
- length: 2
0: 0x05ca38985819 <String[1]: #x>
1: 0x05ca38985831 <String[1]: #y>
Handler Table (size = 0)
Source Position Table (size = 24)
0x31fb5c0888d9 <Other heap object (TRUSTED_BYTE_ARRAY_TYPE)>
25
Showing bytecode.txt. Each output starts with the exact command and version. Run commands from the v2 directory; replace <scratch> with a writable scratch directory.
Addresses and compile timings vary on rerun. --trace-ic is unavailable in this build; --log-ic and %DebugPrint supply the IC evidence. Debug intrinsics are version-specific diagnostics.
Read the evidence, then change one thing
The artefact browser includes complete source and output for bytecode, Map sharing, elements transitions, IC feedback, natural tiering, three deoptimization cases and optimized assembly. Keep the version and flags with a recording. Debug addresses and compilation times vary between runs, while reasons and representations can change with a new engine build. Repeating the experiment is more useful than memorizing a threshold.
For this experiment, “fast” means a path that can use known layouts and narrow arithmetic. It is not a promise of a particular number of nanoseconds. A field load can miss a CPU cache, a process can be descheduled, and a fresh call can pay compilation or collection costs. Separating those sources of latency is what turns an engine fact into an application diagnosis.
Keep the semantic test alongside the performance test. A change that replaces a missing property with undefined, converts arbitrary strings to numbers earlier, or switches to fixed-width arithmetic may simplify the engine’s work by changing the program’s contract. That can be a good product decision when it is intentional. It should not sneak in as an unexplained optimization.
The evidence here gives you a way to ask sharper questions. If a numeric result stays correct through a bailout, recovery worked. If two fresh objects share a Map, identity was never the issue. If a fifth layout changes the IC state while q stays regular, the access site was the right unit of investigation.
Our distance function needed no engine-specific source annotations to benefit. The most helpful application design is often also the simplest: construct comparable data consistently, avoid changing a field’s meaning halfway through its lifetime, and choose explicit numeric storage when that matches the job. Then let measurements tell you whether there is anything left to fix.
End of Inside V8 · 9 levels, Idea to Machine
Where to next
Next in Languages and runtimes · 02 of 06
Go concurrency, from go keyword to OS thread
What makes goroutines and channels different, the patterns they unlock and the bugs they invite, then down through the G-M-P scheduler, the inside of a channel, OS threads and the netpoller, to the two instructions that make stacks growable.
Practical notes
Find why Node and V8 deoptimize a function
Use V8 optimization traces to identify the invalidated assumption, then reproduce it with a controlled input change before changing application code.