Skip to content

perf(ui): memoize per-line diff render blocks - #299

Merged
umputun merged 5 commits into
masterfrom
perf/per-line-render-cache
Jul 31, 2026
Merged

umputun merged 5 commits into
masterfrom
perf/per-line-render-cache

Conversation

@umputun

@umputun umputun commented Jul 31, 2026

Copy link
Copy Markdown
Owner

follow-up to #298, which fixed the cursor-blink re-render and left the real problem open: typing in an annotation still re-rendered every line of the file, and so did every j/k.

renderDiff rebuilt the styled string for all N lines even though only the viewport's ~40 rows are visible. A CPU profile showed the cost is diffuse - ANSI width measurement, grapheme clustering, lipgloss style application spread across renderDiffLine - so there was no hotspot to shave, only work to stop repeating.

each line's rendered block (the diff row plus any annotation rows below it) is now memoized. Typing dirties one row, j/k dirties two, everything else is served from cache.

lines renderDiff before after keystroke before after
500 3.5 ms 0.23 ms 5.1 ms 2.0 ms
2,000 14 ms 0.92 ms 17 ms 4.4 ms
10,000 72 ms 4.8 ms 82 ms 16.4 ms
50,000 337 ms 25 ms 386 ms 78 ms

allocations per render go from 101,178 to 4 at 10k lines, and stay at 4 regardless of diff size or how many annotations the file carries. Page navigation drops 70 ms to 21 ms. Output is byte-identical.

how invalidation works

three parts, and the split matters:

  • comparable render state lives in globalRenderKey, compared by value - self-invalidating, no bump sites to remember
  • per-line state lives in lineRenderFlags, compared per index
  • four inputs are not comparable and cannot live in a key - the style resolver, file.blameData, file.highlighted, file.intraRanges - and go through invalidateRenderCaches()

the cache sits behind a pointer because renderDiff has a value receiver: a plain field would memoize into a copy that gets discarded. Sharing across bubbletea's Model copies is safe because entries are keyed by the state they were rendered under, so identical inputs give identical bytes.

the key holds the resolved diffContentWidth() rather than the raw layout.width/treeWidth it comes from, because that function branches on treePaneHidden() - keying the raw inputs let a t press with treeWidth already 0 change every line's cut width without moving the key.

tests

two, and they are not redundant:

  • TestModel_RenderDiffGolden pins exact bytes across 23 states, but always renders on a fresh model, so it can only catch a wrong render - never a stale one
  • TestModel_RenderDiffCacheMatchesColdRender reaches each state on a model whose cache was dirtied by a different state, which is the only shape that catches a key gap

the second is deliberately not described as a completeness proof. It reaches exactly as far as the state matrix: a field is covered only when two states differ in it and still produce a cache hit. gotchas.md lists the seven fields the matrix isolates and says plainly that the rest are not, because an earlier version named a single blind spot and that implied the others were covered - which is how a missing search.term got through the first time.

diffRenderCache also has direct unit tests, and BenchmarkModel_AnnotatedKeystroke covers the annotated case the other benchmarks miss.

what is still slow

~7.4 ms of the remaining 16.4 ms at 10k lines is inside viewport.SetContent, which runs findLongestLineWidth - an ansi.StringWidth grapheme scan of the whole content - to serve a horizontal-scroll feature revdiff does not use. It scrolls horizontally itself via layout.scrollX and truncates every line to pane width before the viewport sees it, and never sets viewport's xOffset. Unavoidable while handing bubbles a full content string; fixing it means windowed rendering, which is a separate change.

umputun added 5 commits July 30, 2026 14:17
renderDiff rebuilt the styled string for every line of the current file on
every key-driven state change, ~6.7us and ~10 allocs per line. A profile
showed the cost is diffuse - ANSI width measurement, grapheme clustering
and lipgloss style application spread across renderDiffLine - so there is
no hotspot to shave, only work to stop repeating.

each line's rendered block (the diff line plus any annotation rows below
it) is now memoized. Typing dirties one row, j/k dirties two, and the rest
are served from cache. At 10k lines renderDiff goes 72ms -> 4.9ms with
101178 -> 4 allocs, a keystroke 82ms -> 17ms, page navigation 70ms -> 21ms.
Output is byte-identical.

the cache sits behind a pointer because renderDiff has a value receiver: a
plain field would memoize into a copy that is discarded. Comparable render
state lives in globalRenderKey and self-invalidates; the resolver and
file.blameData are not comparable and go through invalidateRenderCaches,
renamed from invalidateAnnotationRows now that it clears both memos, with a
new call in handleBlameLoaded. The blame gutter renders a relative age, so
the key carries a one-minute bucket when blame is on.

two tests guard it. RenderDiffGolden pins exact bytes across 19 states but
always renders fresh, so it cannot catch a stale cache;
RenderDiffCacheMatchesColdRender reaches each state on a model whose cache
was dirtied by a different state, and is the completeness proof for the key.

remaining per-keystroke cost at 10k lines is ~7.4ms inside
viewport.SetContent, which scans every line's display width for a
horizontal-scroll feature revdiff does not use. Not addressed here.
review round 1 found searchTerm missing from globalRenderKey.
highlightSearchMatches locates the highlighted byte range from
m.search.term, so the term decides which characters a matched row
highlights, not merely whether it is highlighted. submitSearch rewrites
term and matches without invalidating, so a second search matching the
same lines - /return then /eturn - served every matched row from cache
with the previous term's span.

the cache test could not see it. Its matrix had one search state, so
every pair flipped searchMatch and missed the cache; term-A to term-B is
the only shape that hits. Added that state, confirmed it fails, then
added searchTerm to the key.

also from the same round:

the golden baked an absolute blame instant while renderDiff stamps
time.Now(), and RelativeAge buckets by whole hours under 24h - the
fixture held "7h" and would have gone red at the next hour boundary and
stayed red. Blame times are now an offset from now, always rendering
"3h".

lastLen survived rebase and clear, so switching from a 50k-line diff to a
small file pre-sized the builder from the old content. Reset in both.

matrix gained word-diff and empty-body-annotation states, the latter
covering hasComment, which distinguishes no-annotation from an
annotation with an empty body - reachable via --annotations, and a case
where skipping paint while the height query still reserves the row is
exactly the drift the annotation chokepoint exists to prevent.

the comment calling that test a completeness proof for globalRenderKey
was wrong and is corrected here and in gotchas.md: it reaches exactly as
far as the state matrix, and a field is covered only when two states
differ in it and still hit the cache. blameMinute remains uncovered -
cold and warm renders are microseconds apart, so they always share a
bucket.
review round 2, eight findings, all minor. No majors this round.

lineRenderFlags ran annotationKey's Sprintf per line on every render,
including renders that were entirely cache hits, for any file carrying at
least one line annotation - the annotate-and-keep-reading workflow the
cache exists for. The render-path map is now keyed on a comparable
annotLineKey. Allocations with annotations present now match the
unannotated case, and BenchmarkModel_AnnotatedKeystroke covers the shape
no benchmark reached.

focus and viewport.Width are out of globalRenderKey. Nothing in the
render path reads viewport.Width, and every focus read inside the cached
loop is captured per line by lineRenderFlags, so both only forced whole
cache drops - focus on every Tab and every click into the tree, each
paying a cold rebuild.

lastLen no longer resets in rebase. That skipped b.Grow on exactly the
renders that rebuild from scratch while keeping it for the all-hits
renders that were already cheap. The reset in clear covers the case round
1 raised, since every content-replacing path goes through it.

refreshDiff now invalidates itself instead of depending on its single
caller to have done it first.

the invalidation contract said two non-comparable render inputs; there
are four. file.highlighted and file.intraRanges are also outside the key,
safe today only because of where they happen to be mutated. Both godocs
and gotchas.md now say so. Removing focus from the key exposed a second
instance of exactly that hazard in an existing test, which assigned
file.highlighted after a load had already cached.

benchModel installed highlighting after handleFileLoaded had filled the
cache, so the render benchmarks were assembling unhighlighted blocks.
Corrected; B/op moves 860KB to 1.09MB at 10k lines and the timing is
unchanged, so the headline numbers stand.

the note naming blameMinute as the one remaining matrix blind spot was
worse than naming none - it implied the other fields were covered, which
is the inference that let search.term ship in the first place. gotchas.md
now lists the six fields the matrix actually isolates and says plainly
that the rest are not.

diffRenderCache gains direct unit tests; it had none.
…ew.go

round 2 left this as an open question rather than a finding.
invalidateRenderCaches clears diffRenderCache, but lived in annotate.go
alongside the annotation rows it also clears, while the cache, its type,
its clear method and every other use sat in diffview.go. A maintainer
adding a runtime color toggle found clear() with no visible caller and no
contract, and a missed invalidation is silent.

moved next to diffRenderCache. The three tests pinning it moved to
diffview_test.go with it, renamed off AnnotationRows since they cover
both memos, and each now asserts the diff blocks are dropped - none of
them did, which is how the function could have stopped clearing
renderCache without a test noticing.

the file-load test asserts no block from the previous file survives
rather than that the cache is empty: handleFileLoaded re-renders after
invalidating, so a warm cache for the new file is correct.
review round 3, pre-merge, two minors.

globalRenderKey held the raw layout.width and treeWidth, but every width
consumer in the render path - applyHorizontalScroll, plainHorizontalCut,
extendLineBg, wrapWidth, annotationVisualRows - goes through
diffContentWidth(), which branches on treePaneHidden() = treeHidden ||
(singleFile && mdTOC == nil). None of those three were in the key.

reachable: a single-file diff sets treeWidth to 0, a later transition
back to multi-file clears singleFile without recomputing treeWidth, and
`t` then sets treeHidden with treeWidth already 0. No key field moves, so
every line keeps blocks cut and padded to width-6 while diffContentWidth
now returns width-4 - two columns of content hidden and the background
fill two columns short, persisting until scrollX or a resize.

the key now holds the resolved diffContentWidth() instead, which cannot
drift from what the render path consumes and collapses five inputs into
one. Verified no render-path site reads layout.width or treeWidth outside
diffContentWidth itself. This is how annotCacheKey already keys, on the
resolved wrapW. A tree-hidden state isolates it: confirmed to fail on two
subtests when contentWidth is dropped from the key.

gotchas.md still described the invalidation contract as two
non-comparable inputs while both godocs said four - round 2's fix reached
the code and missed the file CLAUDE.md and the review profile designate
as the rendering-invariants reference. It mentioned file.highlighted only
as a benchmark caveat, which reads as a harness quirk rather than the
production obligation it is, and never mentioned file.intraRanges. Now
names all four and points at refreshDiff as the shape to copy.
Copilot AI review requested due to automatic review settings July 31, 2026 05:18

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@umputun
umputun merged commit 2a33de8 into master Jul 31, 2026
5 checks passed
@umputun
umputun deleted the perf/per-line-render-cache branch July 31, 2026 05:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants