Goal: compare different paths to the same final image
An element’s width changes to 120, then 140, then 160, and its final displayed width is 160. Measuring after every change follows a different execution path from batching the writes before one measurement. This lesson represents stale results with dirty flags and performs required work when a model operation needs it. The prerequisites are CSS application, layout, painting, and the event loop. The goal is to explain why the same final value can involve different modeled recalculation counts.
The layout and paint counters are executions of the teaching rules, not CPU time or real-browser speed ratios. In the event-loop and rendering model, compare operation cards under fixed rules: a color change invalidates paint, while a width change invalidates layout and paint. Those rules do not describe every CSS property or browser optimization. State the measurement name, its unit, and what it includes. A count is useful evidence only when the competing sequences perform comparable work and preserve the output that the task actually requires.
Keep input state, computed geometry, and painted output distinct
Changing a style input can make the stored document state newer than previously computed geometry. Dirty flags allow several changes to accumulate before recomputation. If one variable is repeatedly overwritten with the specified width, computed box width, and last painted width, the interface cannot show which representation is stale. Store them separately and compare the state before and after each update. A dirty flag records a dependency, not an error or an unfinished assignment.
Dependencies can extend beyond the edited node. Longer child content may affect a parent’s size or later siblings’ positions. This small fixed-layout model gives width changes a declared layout dependency and follows them with paint. Compare that with a color-only change while observing exactly which range the model recomputes. Do not claim that a browser always relayouts the entire document after every mutation, or that it can always limit the work to one element. The interesting question is which dependent results have become stale under the selected rules.
A geometry read can require current layout information
An API such as getBoundingClientRect must return geometry appropriate to its requested result. Pending changes can require synchronous updates before that information is available. This does not mean that every geometry read necessarily performs a full-page layout. The model uses a precise rule: a read operation performs one layout if layoutDirty is true and then clears that flag. A read when the layout is already current adds no layout count.
| Operation sequence | layoutDirty transitions | Layout count |
|---|---|---|
| width120 → read | true → false | 1 |
| width140 → read | true → false | 2 |
| width160 → read | true → false | 3 |
| width120 → width140 → width160 → read | Stay dirty until one final read | 1 |
Batching must preserve the meaning of observation
Batching writes before one read can reduce work, but moving every read to the end is not universally correct. If a program uses intermediate widths 120 and 140 to make decisions, moving those observations changes its behavior. Establish which inputs must be read first, which writes are independent, and which final state must be observed. Check values and required behavior alongside operation counts. A smaller count obtained by computing a different result is not an optimization of the same task.
The implementation example requires only the final width. A requirement to record every intermediate geometry would need different expected observations. Without a stated comparison contract, omitting required work can appear to be an improvement. Preserve the same inputs, final outputs, and necessary observations before comparing counts. Never turn the model’s count ratio into a claimed real-device speedup. Actual implementations have additional work and optimizations that this deterministic exercise intentionally does not measure.
Implementation: count interleaved and batched updates
The independent program below stores width, color, dirty flags, and layout and paint counts. A changed width invalidates layout and paint. A read or frame performs a needed layout, whereas a changed color invalidates paint alone. Interleaving three writes with three reads produces three layouts; batching the writes produces one; a color-only example produces none. The printed values are 3 1 0, and both width examples finish at 160.
A read can complete layout before a frame without completing paint. Separate flags allow the later frame to paint once without recalculating current geometry. This model also explicitly treats assigning the same width again as no new invalidation. It is not a complete implementation of browser style computation, layers, compositing, or every attribute assignment. Test final state and counts together so that the model cannot appear to improve by returning stale geometry or skipping a required frame.
function simulate(operations) {
let width = 100, color = 'black', layoutDirty = false, paintDirty = false;
let layouts = 0, paints = 0;
function layout() { if (layoutDirty) { layouts++; layoutDirty = false; } }
for (const [kind, value] of operations) {
if (kind === 'width' && width !== value) {
width = value; layoutDirty = true; paintDirty = true;
} else if (kind === 'color' && color !== value) {
color = value; paintDirty = true;
} else if (kind === 'read') {
layout();
} else if (kind === 'frame') {
layout();
if (paintDirty) { paints++; paintDirty = false; }
}
}
return {width, color, layouts, paints};
}
const interleaved = simulate([['width',120],['read'],['width',140],['read'],['width',160],['read'],['frame']]);
const batched = simulate([['width',120],['width',140],['width',160],['read'],['frame']]);
const colorOnly = simulate([['color','red'],['frame']]);
console.assert(interleaved.layouts === 3 && batched.layouts === 1);
console.assert(interleaved.width === batched.width && batched.width === 160);
console.assert(colorOnly.layouts === 0 && colorOnly.paints === 1);
console.log(interleaved.layouts, batched.layouts, colorOnly.layouts);Failure: repeatedly invalidating the result needed by a read
A loop that writes width and immediately measures it can make every previous layout stale before the next read. The sequence removes its own opportunity to combine changes. Repair the task by grouping independent writes and placing necessary reads at a point that preserves dependencies. Returning old geometry to reduce the counter is not a repair. If a required observation or final value is wrong, a lower count still fails the task.
Compare a color-only change, an identical-width assignment, a read without changes, and input without a rendering opportunity. Some cases need paint but no layout; others change document state while leaving the displayed image old. A zero layout count alone does not mean that nothing happened. For an actual browser experiment, record API results separately from development-tool measurements. The model counter must not be relabeled as measured browser performance merely because both are related to layout.
A rendering callback is not a general display-completion signal
requestAnimationFrame schedules a callback in relation to rendering updates, but neither the registration returning nor the callback beginning alone proves that changed pixels have reached the user. A frame card is an abstract model operation that advances required work at a selected rendering opportunity. A browser has further conditions involving visibility and timing. Separate scheduling an update, obtaining required geometry, producing drawing work, and observing a displayed image. This avoids presenting an ordering demonstration as a precise account of hardware scanout or display latency.
Exercise: reduce recalculations while preserving results
Reorganize the repair task’s alternating width writes and geometry reads while preserving the required final value. Compare layout count, final width, paint count, and last displayed state before and after the repair. Repeat with different widths. Hard-coding the expected text, ignoring a read, or deleting required painting does not satisfy the dependency contract, even if one counter becomes smaller.
Predict one transition before stepping forward, then record which operation sets each dirty flag and which operation clears it. In comparisons, align meaningful events such as width changes, reads, layout, and paint rather than pairing arbitrary frame numbers. If the edited sequence has fewer steps, show removed work explicitly. This explains the cause of a count change. Combining these observations with DOM mutation, event dispatch, and queue scheduling gives a complete path for the browser project’s integrated exercise: a click changes state that eventually becomes a visible update.