Skip to content

perf(parser): pre-size lexer token vectors to kill reallocation churn (-10.8% heap) - #1587

Merged
robcohen merged 2 commits into
mainfrom
perf/lexer-presize-tokens
Jun 25, 2026
Merged

robcohen merged 2 commits into
mainfrom
perf/lexer-presize-tokens

Conversation

@robcohen

Copy link
Copy Markdown
Member

What

Profiling-driven optimization. Pre-sizes the two lexer token vectors that the new nightly profiling (the profiling data branch) flagged as the largest allocations — eliminating reallocation churn.

tokenize_inner (logos_lexer.rs) and lossless_kind_tokens (cst/lossless_tokens.rs) both built their output Vec from Vec::new() and grew via push, reallocating ~17× as the geometric doubling kicked in. A beancount token averages ~4 bytes of source, so Vec::with_capacity(source.len() / 4) reserves close to the final count up front.

Measured impact (10k-txn workload, dhat + cachegrind)

Metric Before After Δ
tokenize_inner allocations 20.97 MB in 17 blocks 10.25 MB in 1 block churn eliminated
Total heap allocated 158.7 MB 141.6 MB −17.1 MB (−10.8%)
Instructions 1,121,094,109 1,118,784,650 −2.3M

(lossless_kind_tokens dropped out of the top-4 allocators entirely.)

Why it's safe

Allocation-only change — no behavioral difference. cargo test -p rustledger-parser passes; clippy -D warnings clean. The win will show up as a step down in heap_total_bytes on the next nightly profiling trend point.

How it was found

This is the payoff of the profiling work (slices 1–4): the dhat heap profile ranked these two Vec::new() sites #1 and #2 by bytes, and cachegrind confirmed ~12% of CPU was in malloc/free. More targets remain (the Transaction::clone ×2 per txn, the 190k-allocation walk_descendants_once, happy-path error-scan allocations) — follow-ups.

🤖 Generated with Claude Code

Copilot AI review requested due to automatic review settings June 25, 2026 02:49
@robcohen
robcohen requested a review from a team as a code owner June 25, 2026 02:49
@codecov

codecov Bot commented Jun 25, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Performance-focused change in rustledger-parser to reduce heap allocation churn during lexing/token stream construction by reserving capacity up front for the primary token vectors.

Changes:

  • Pre-allocate capacity for the AST lexer token output vector in tokenize_inner.
  • Pre-allocate capacity for the CST “lossless kind token” output vector in lossless_kind_tokens.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
crates/rustledger-parser/src/logos_lexer.rs Pre-sizes the lexer output Vec to reduce reallocations during tokenization.
crates/rustledger-parser/src/cst/lossless_tokens.rs Pre-sizes the CST lossless (SyntaxKind, Range) output Vec to reduce reallocations.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@github-actions

github-actions Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 41.6ms ± 5.3ms 23.8 MB
beancount 931.7ms ± 9ms 50.7 MB
Comparison 22.4x faster 2.1x less

vs main branch (2026-06-25)

Metric main this PR Change
Time 37.4ms 41.6ms +11.2% 🔴
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 792
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

@robcohen

Copy link
Copy Markdown
Member Author

Good catch — capped both reservations at TOKEN_CAPACITY_CAP (4M entries, ~100MB; far above any real ledger). A pathological input (e.g. a giant whitespace run that lexes to few tokens) now grows normally past the cap instead of amplifying len/4 into a multi-GB up-front reservation. Keeps the win for real files; respects the parser's graceful-on-malformed-input contract.

robcohen added 2 commits June 25, 2026 03:39
dhat profiling (the new profiling data branch) ranked tokenize_inner and
lossless_kind_tokens as the #1/#2 allocators -- both grew an unsized Vec via
push, reallocating ~17x. Reserve Vec::with_capacity(source.len() / 4) (~4 bytes
per beancount token). Measured on a 10k-txn workload: total heap allocated
158.7MB -> 141.6MB (-10.8%); tokenize_inner 17 allocations -> 1. Parser tests +
clippy clean; allocation-only, behavior-preserving.
@robcohen
robcohen force-pushed the perf/lexer-presize-tokens branch from f5daf70 to afb0745 Compare June 25, 2026 03:39
@robcohen
robcohen merged commit 69d3780 into main Jun 25, 2026
49 checks passed
@robcohen
robcohen deleted the perf/lexer-presize-tokens branch June 25, 2026 04:02
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