Repository navigation
perf(ui): memoize per-line diff render blocks - #299
Merged
Merged
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.renderDiffrebuilt 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 acrossrenderDiffLine- 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/kdirties two, everything else is served from cache.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:
globalRenderKey, compared by value - self-invalidating, no bump sites to rememberlineRenderFlags, compared per indexfile.blameData,file.highlighted,file.intraRanges- and go throughinvalidateRenderCaches()the cache sits behind a pointer because
renderDiffhas 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 rawlayout.width/treeWidthit comes from, because that function branches ontreePaneHidden()- keying the raw inputs let atpress withtreeWidthalready 0 change every line's cut width without moving the key.tests
two, and they are not redundant:
TestModel_RenderDiffGoldenpins exact bytes across 23 states, but always renders on a fresh model, so it can only catch a wrong render - never a stale oneTestModel_RenderDiffCacheMatchesColdRenderreaches each state on a model whose cache was dirtied by a different state, which is the only shape that catches a key gapthe 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.mdlists 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 missingsearch.termgot through the first time.diffRenderCachealso has direct unit tests, andBenchmarkModel_AnnotatedKeystrokecovers 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 runsfindLongestLineWidth- anansi.StringWidthgrapheme scan of the whole content - to serve a horizontal-scroll feature revdiff does not use. It scrolls horizontally itself vialayout.scrollXand truncates every line to pane width before the viewport sees it, and never sets viewport'sxOffset. Unavoidable while handing bubbles a full content string; fixing it means windowed rendering, which is a separate change.