Skip to content

perf(source-map): lazy-build lineStarts in parseMdWithSourceMap - #109

Merged
luojiyin1987 merged 1 commit into
masterfrom
perf/lazy-line-starts
Sep 7, 2026
Merged

luojiyin1987 merged 1 commit into
masterfrom
perf/lazy-line-starts

Conversation

@luojiyin1987

@luojiyin1987 luojiyin1987 commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

What

Defer computeLineStarts(md) in parseMdWithSourceMap() from eager to lazy initialization via ??=.

Why

getRaw() never uses lineStarts, but every parseMdWithSourceMap() call currently scans the full Markdown source to build a number[] line index. For getRaw()-only callers this array is pure waste — one number per line of input, allocated and immediately GC'd.

A 256 KiB Markdown file with ~4000 lines allocates a number[] of 4000+ entries (32 KiB+) that is never read.

Changes

  • Replace const lineStarts = computeLineStarts(md) with let lineStarts: number[] | undefined.
  • Insert lineStarts ??= computeLineStarts(md) at the top of getSourceRange() and getFieldSourceRange() — the only two call sites that need it.
  • 3 insertions, 1 deletion.

Impact

  • Memory: for getRaw()-only callers, skips the number[] allocation entirely (saves ~1 entry per line of input).
  • CPU: marginal (~6 ms at 256 KiB) from skipping the Markdown scan — not the primary goal.

Verification

  • 1961/1961 tests pass

computeLineStarts(md) was eagerly called on every parseMdWithSourceMap()
invocation, but getRaw() never uses it. Defer to first use in
getSourceRange() / getFieldSourceRange() via nullish coalescing assignment.

For getRaw()-only callers this skips the full Markdown scan and number[]
allocation entirely.
@luojiyin1987
luojiyin1987 merged commit 52185eb into master Sep 7, 2026
14 checks passed
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.

1 participant