Repository navigation
perf(html): stream tokens line by line instead of materialising all lines - #1528
TheNetherWatcher wants to merge 1 commit into
Conversation
|
Thanks for this, and for the careful measurements and output-equivalence testing. They made the trade-offs easy to evaluate. I've landed a similar change in 9d60314 that takes the same approach (stream without line numbers, buffer only when the line count is needed), but does it by changing I compared both branches on a 1 MB Go file. Without line numbers, peak heap is the same for both, down to the cost of lexing alone. This PR is a little ahead elsewhere: about 5% fewer total allocations from reusing the line buffer, and about 2.5 MB lower peak with line numbers. I decided the single, iterator-based implementation was worth that small difference. Closing in favour of that commit, but thanks again for digging into this. |
The HTML formatter collects every token into a slice (
slices.Collect(iterator)inFormat), thenwriteHTMLcallschroma.SplitTokensIntoLines, which builds a second copy of all tokens grouped by line. Both stay alive for the whole render even though output is written one line at a time. On a 1 MB Go file lexing alone peaks around 4.8 MB, while formatting peaks around 27 MB.This PR:
forEachLinehelper that splits lines exactly likeSplitTokensIntoLines(including dropping the empty trailing line) but reuses one line buffer instead of materialising every lineFormatstreams tokens straight from the lexer and never builds the token slicewriteHTMLtakes the token sequence and the line count; no public API changeResults
Peak live heap on real Go source, median of 5:
Runtime is unchanged within noise (−1.6% geomean, 1 MB default 633 → 611 ms). Bytes allocated drop 10–14% without line numbers and 5–6% with them.
Correctness
forEachLineagainstSplitTokensIntoLines.masterfor every lexer testdata file, a set of edge cases, and 3,000 random token streams across 11 option combinations: all 36,113 outputs are byte-identical.go test ./...andgolangci-lint run ./formatters/html/pass.One behaviour difference: without line numbers, if a lexer panics mid-stream, the writer may already have received partial HTML before the error is returned (previously nothing was written). The error is still returned, and the terminal formatters already behave this way.
The SVG formatter has the same collect-then-split pattern; happy to follow up there if this looks good.