Skip to content

perf(sourcemap): stop rescanning a long line for each unedited chunk - #387

Open
tycrimm wants to merge 1 commit into
Rich-Harris:masterfrom
tycrimm:perf/unedited-chunk-newline
Open

tycrimm wants to merge 1 commit into
Rich-Harris:masterfrom
tycrimm:perf/unedited-chunk-newline

Conversation

@tycrimm

@tycrimm tycrimm commented Nov 6, 2026 •

Copy link
Copy Markdown

Since v1.3.0 (#339), generateMap() / generateDecodedMap() without hires slow down quadratically on long lines that are split into many chunks, i.e. minified code going through a bundler. Bundling echarts' minified ESM build with rollup 4.68 and sourcemap: true takes about 2.5x as long in generate() as with this fix.

Cause

The lo-res walk added in #339 finds the end of each line with original.indexOf('\n', i) from the start of every unedited chunk. That search doesn't stop at chunk.end; it runs to the next line break in the whole string. With K chunks on a line of length L, generating the map costs O(K × L).

Fix

Mappings keeps the result of the last search with its start position and reuses it while i lies between that start and the line break it found. It recomputes when the walk goes backwards (moved chunks) or past the cached break, and the cache resets per MagicString in addMagicString. Hires modes are untouched. The output doesn't change.

Benchmarks

Node 24.22.1, Apple M2 Max, median of 11 runs. Mappings are byte-identical before and after in every row.

rollup 4.68, echarts 6.1.0 dist/echarts.esm.min.mjs (1 MB, one line), bundle.generate() with rollup's bundled copy of magic-string patched:

case sourcemap before after speedup
echarts alone false 60 ms 61 ms —
echarts alone true 305 ms 124 ms 2.5×
with renamed identifiers (5,569 $1 renames) false 67 ms 69 ms —
with renamed identifiers (5,569 $1 renames) true 304 ms 113 ms 2.7×

The cost of sourcemap: true drops from ~240 ms to ~45–65 ms.

magic-string generateMap() after overwriting every identifier, median of 7 runs:

size edits one line, before one line, after speedup 40-char lines, before 40-char lines, after speedup
49 KB 5,000 3.8 ms 0.9 ms 4.2× 0.8 ms 0.8 ms —
98 KB 10,000 13.7 ms 1.1 ms 12× 1.5 ms 1.5 ms —
195 KB 20,000 50.2 ms 2.0 ms 25× 2.9 ms 2.8 ms —
391 KB 40,000 193.1 ms 4.0 ms 48× 6.1 ms 5.5 ms 1.1×
781 KB 80,000 756.3 ms 8.3 ms 91× 11.7 ms 11.8 ms —
rollup / echarts benchmark

bun add rollup echarts, copy node_modules/rollup to node_modules/rollup-patched with this change applied to its bundled Mappings, then node real-world.mjs rollup 11 plain, node real-world.mjs rollup-patched 11 plain (and collide).

// Bundles echarts' minified ESM build (one ~1 MB line) with rollup and times
// bundle.generate(). `plain` bundles echarts alone; `collide` first runs a module
// declaring every 1-2 character identifier, so rollup also renames each
// colliding top-level name in echarts.
// usage: node real-world.mjs <rollup package> <runs> <plain|collide>
import { createHash } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { createRequire } from 'node:module'

const [pkg = 'rollup', runs = '5', mode = 'collide'] = process.argv.slice(2)
const { rollup } = await import(pkg)
const require = createRequire(import.meta.url)
const echartsPath = require.resolve('echarts/dist/echarts.esm.min.mjs')
const echarts = readFileSync(echartsPath, 'utf8')

const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$'
const reserved = new Set(['do', 'if', 'in'])
const names = [...chars]
for (const a of chars) {
  for (const b of `${chars}0123456789`)
    names.push(a + b)
}
const declared = names.filter(n => !reserved.has(n))
const modules = {
  'entry.js': `${mode === 'plain' ? '' : `import 'names.js'\n`}import * as echarts from 'echarts'\nconsole.log(echarts)\n`,
  'names.js': `var ${declared.map((n, i) => `${n}=${i}`).join(',')}\nconsole.log([${declared.join(',')}])\n`,
  'echarts': echarts,
}

async function build(sourcemap) {
  const bundle = await rollup({
    input: 'entry.js',
    plugins: [{ name: 'virtual', resolveId: id => id, load: id => modules[id] }],
  })
  const t0 = performance.now()
  const { output } = await bundle.generate({ format: 'es', sourcemap })
  const ms = performance.now() - t0
  return { ms, output: output[0] }
}

const median = xs => xs.toSorted((a, b) => a - b)[xs.length >> 1]
for (const sourcemap of [false, true]) {
  const times = []
  let output
  for (let r = 0; r < Number(runs); r++)
    ({ ms: times[r], output } = await build(sourcemap))
  const renamed = (output.code.match(/\$1\b/g) ?? []).length
  const hash = output.map ? createHash('sha1').update(output.map.mappings).digest('hex').slice(0, 10) : '-'
  console.log(`${pkg} ${mode} sourcemap=${sourcemap} generate median ${median(times).toFixed(0)} ms (${times.map(t => t.toFixed(0)).join(', ')}) renamed=${renamed} mappings=${hash}`)
}
generateMap micro-benchmark

node micro.mjs <path to dist/index.mjs>

// generateMap() (default lo-res) after renaming every identifier of a minified
// one-line source, plus the same source split into short lines as a control.
// usage: node micro.mjs <path to magic-string dist/index.mjs>
import { createHash } from 'node:crypto'

const { MagicString } = await import(process.argv[2])
const median = xs => xs.toSorted((a, b) => a - b)[xs.length >> 1]

for (const layout of ['one line', '40-char lines']) {
  for (const n of [5_000, 10_000, 20_000, 40_000, 80_000]) {
    let code = ''
    const starts = []
    for (let i = 0; i < n; i++) {
      starts.push(code.length)
      code += `a${i % 10}=b(c,d);`
      if (layout !== 'one line' && i % 4 === 3)
        code += '\n'
    }
    const s = new MagicString(code)
    for (const p of starts)
      s.overwrite(p, p + 2, 'xx')

    const times = []
    let map
    for (let r = 0; r < 7; r++) {
      const t0 = performance.now()
      map = s.generateMap({ source: 'in.js' })
      times.push(performance.now() - t0)
    }
    const hash = createHash('sha1').update(map.mappings).digest('hex').slice(0, 10)
    console.log(`${layout}\t${(code.length / 1024).toFixed(0)} KB\t${n} edits\t${median(times).toFixed(1)} ms\t${hash}`)
  }
}

Verification

  • New tests pin the lo-res mappings for many edits on one line, for chunks moved before earlier ones, and for a bundle whose sources each need their own line break search. Each of the three invalidation conditions fails at least one of them when removed; all pass on main too.
  • pnpm test: 497 passed. pnpm lint and pnpm typecheck clean.
  • Differential fuzz against main (random overwrite/remove/appendLeft/prependRight/move/addSourcemapLocation/update sequences, generateMap and Bundle#generateMap with hires false/true/'boundary'): 25,000 sequences, identical mappings.

Relation to #383

#383 also removes this scan, as part of treating every ECMAScript line terminator as a line break, by reading line starts from the locator. This PR is the narrow perf fix on its own, with no change to output. Happy to close this if #383 lands first, or rebase whichever lands second; with this merged first, #383 would just drop the nextNewline helper.

This PR was prepared with the help of an AI agent (Claude Code).

🤖 Generated with Claude Code

The lo-res walk searched for the next line break from the start of every
unedited chunk. On a long line split into many chunks (minified code with
renamed identifiers) each search ran to the end of the line, so the walk
took O(chunks x line length). Reuse the previous search while the chunk
starts between where it began and the line break it found.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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