GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing github.com — feat: port performance fixes and ignoreList propagation from rspack-sources by alexander-akait · Pull Request #226 · webpack/webpack-sources Conversation
Member
Four changes inspired by rspack-sources:
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page. All reactions
|
There was an error while loading. Please reload this page.
|
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
|
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
Merging this PR will improve performance by 15.64%
|
| Mode | Benchmark | BASE |
HEAD |
Efficiency | |
|---|---|---|---|---|---|
| ❌ | Memory | size-only-source memory: new SizeOnlySource() |
60.6 KB | 112.5 KB | -46.18% |
| ❌ | Memory | cached-source memory: construct from cachedData (no warm-up) |
392 B | 648 B | -39.51% |
| ❌ | Memory | concat-source memory: source() concatenates children |
245 KB | 401.3 KB | -38.95% |
| ❌ | Simulation | cached-source: size() (cached) |
30.1 µs | 45.8 µs | -34.31% |
| ❌ | Simulation | concat-source: buffers() (10 raw) |
84.2 µs | 123.1 µs | -31.61% |
| ❌ | Simulation | compat-source: CompatSource.from(SourceLike) |
58 µs | 81.6 µs | -28.9% |
| ❌ | Memory | compat-source memory: CompatSource.from() short-circuits on Source |
648 B | 904 B | -28.32% |
| ❌ | Simulation | concat-source: getChildren() |
112.5 µs | 153.8 µs | -26.85% |
| ❌ | Simulation | concat-source: addAllSkipOptimizing() |
107.1 µs | 142.7 µs | -24.92% |
| ❌ | Simulation | concat-source: buffers() (nested 4x10 raw) |
131.2 µs | 174.6 µs | -24.85% |
| ❌ | Simulation | concat-source: add() x50 |
115.7 µs | 150.6 µs | -23.13% |
| ❌ | Simulation | concat-source: source() (10 raw) |
118.6 µs | 154.2 µs | -23.11% |
| ❌ | Simulation | raw-source: new RawSource(buffer, true) |
79.7 µs | 103.7 µs | -23.1% |
| ❌ | Simulation | raw-source: map() |
87.8 µs | 114.1 µs | -23.07% |
| ❌ | Simulation | raw-source: new RawSource(buffer) |
79.9 µs | 103.7 µs | -22.98% |
| ❌ | Simulation | concat-source: source() (mixed) |
120.4 µs | 156.3 µs | -22.97% |
| ❌ | Simulation | raw-source: new RawSource(string) |
81.8 µs | 105.5 µs | -22.51% |
| ❌ | Simulation | raw-source: buffer() (from buffer) |
87.4 µs | 112.1 µs | -22.01% |
| ❌ | Simulation | raw-source: source() (string) |
89.2 µs | 113.5 µs | -21.39% |
| ❌ | Simulation | raw-source: buffers() (from buffer) |
94.4 µs | 119.5 µs | -21.01% |
| ... | ... | ... | ... | ... | ... |
ℹ️ Only the first 20 benchmarks are displayed. Go to the app to view all benchmarks.
Tip
Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.
Comparing claude/rspack-sources-perf-JEowh (5c6c822) with main (5c5ed84)
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
This PR ports several performance optimizations and sourcemap metadata propagation improvements (notably ignoreList, plus debugId/sourceRoot preservation) into webpack-sources’ stream-based source/map pipeline.
Changes:
ReplaceSource.streamChunks by avoiding splitIntoLines for the common single-line replacement case, and by reusing a wrapped OriginalSource line-split cache when available.OriginalSource.originalLines() to memoize splitIntoLines across repeated reads.getFromStreamChunks (shared padding helper) and propagate per-source ignoreList via an extended onSource(..., info) contract.debugId and sourceRoot when SourceMapSource has an inner map.Copilot reviewed 9 out of 10 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
types.d.ts |
Updates typings for the new SourceInfo propagation and OriginalSource.originalLines() API. |
lib/helpers/streamChunks.js |
Extends the onSource callback contract with optional info metadata. |
lib/helpers/streamChunksOfSourceMap.js |
Emits per-source ignored info derived from ignoreList. |
lib/helpers/streamChunksOfCombinedSourceMap.js |
Threads SourceInfo through combined sourcemap streaming (inner/outer composition). |
lib/helpers/getFromStreamChunks.js |
Collects ignoreList and optimizes array padding via setAtIndex. |
lib/OriginalSource.js |
Adds memoized originalLines() and clears it in clearCache. |
lib/ReplaceSource.js |
Adds single-line fast paths and reuses wrapped-source line caching; forwards info in onSource. |
lib/ConcatSource.js |
Propagates SourceInfo and unions ignored flags across children. |
lib/SourceMapSource.js |
Re-attaches debugId/sourceRoot after getMap/getSourceAndMap round-trips when an inner map exists. |
test/SourceMapSource.js |
Adds regression tests for ignoreList propagation and debugId/sourceRoot preservation. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| if (sourceIndexMapping[sourceIndex] === -2) { | ||
| let globalIndex = sourceMapping.get(innerSourceName); | ||
| if (globalIndex === undefined) { | ||
| sourceMapping.set(source, (globalIndex = sourceMapping.size)); |
| }); | ||
|
|
||
| it("preserves ignoreList through ConcatSource and ReplaceSource", () => { | ||
| // Build two SourceMapSources, each marking source 0 as ignored. |
There was an error while loading. Please reload this page.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@ ## main #226 +/- ## ========================================== + Coverage 97.58% 97.65% +0.06% ========================================== Files 25 25 Lines 2069 2087 +18 Branches 668 689 +21 ========================================== + Hits 2019 2038 +19 + Misses 47 46 -1 Partials 3 3
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Sorry, something went wrong.
There was an error while loading. Please reload this page.
…rces port Three follow-ups to commit 16f8fc2, prompted by the CodSpeed report on PR #226 and local re-measurement that showed several of those numbers were noise from CodSpeed's "different runtime environments" warning: 1. ReplaceSource.streamChunks: drop the per-call `.bind(innerSource)` allocation. Hoist the duck-type check to a boolean and call `innerSource.originalLines()` directly on demand. One fewer bound closure per streamChunks invocation. 2. OriginalSource: stop eagerly initializing `this._lines = undefined` in the constructor. The slot is only ever populated when a caller invokes `originalLines()` (typically ReplaceSource for the wrapped-source line cache). Most OriginalSources are constructed, hashed, and serialized without ever touching it, so the eager init was a wasted hidden-class transition on the construction hot path. clearCache now also guards the assignment so it doesn't add the slot on instances that never asked for the cache. 3. benchmark/with-codspeed.mjs: double-pump global.gc() before the instrumented run. V8 needs two passes for a thorough collection — a single call leaves transient warmup allocations in old-gen and they pollute the per-task memory numbers CodSpeed records. Local 3-run median on `cached-source: new CachedSource()` (the bench CodSpeed flagged as -10.47%): main 254k ops/s → branch 267k ops/s (+4.9%). Full test suite (89,873 tests) still passes, types clean, lint clean.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Copilot reviewed 13 out of 14 changed files in this pull request and generated 1 comment.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| if (sourceIndexMapping[sourceIndex] === -2) { | ||
| let globalIndex = sourceMapping.get(innerSourceName); | ||
| if (globalIndex === undefined) { | ||
| sourceMapping.set(source, (globalIndex = sourceMapping.size)); |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Copilot reviewed 7 out of 8 changed files in this pull request and generated no new comments.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Copilot reviewed 7 out of 8 changed files in this pull request and generated 3 comments.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| /** | ||
| * Index-stabilising comparator for v8 < 7.0 (pre-stable Array.prototype.sort). | ||
| * Unreachable on any modern Node — the `hasStableSort` guard above wins on | ||
| * every supported runtime, so coverage tools never see it execute. | ||
| * @param {Replacement} a a | ||
| * @param {Replacement} b b | ||
| * @returns {number} order | ||
| */ | ||
| /* istanbul ignore next */ | ||
| const compareUnstableFallback = (a, b) => { | ||
| const diff1 = a.start - b.start; |
| this.name = name; | ||
| // V8 < 7.0 only — unreachable on any supported Node. | ||
| /* istanbul ignore if */ | ||
| if (!hasStableSort) { | ||
| this.index = -1; | ||
| } |
| "name": "webpack-sources", | ||
| "version": "3.5.0", | ||
| "description": "Source code handling classes for webpack", | ||
| "keywords": [ | ||
| "webpack", | ||
| "source-map" | ||
| ], | ||
| "keywords": ["webpack", "source-map"], | ||
| "homepage": "https://github.com/webpack/webpack-sources#readme", |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Copilot reviewed 3 out of 3 changed files in this pull request and generated no new comments.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| "version": "3.5.0", | ||
| "description": "Source code handling classes for webpack", | ||
| "keywords": [ | ||
| "webpack", | ||
| "source-map" | ||
| ], | ||
| "keywords": ["webpack", "source-map"], | ||
| "homepage": "https://github.com/webpack/webpack-sources#readme", | ||
| "bugs": { | ||
| "url": "https://github.com/webpack/webpack-sources/issues" | ||
| }, | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "git+https://github.com/webpack/webpack-sources.git" | ||
| }, | ||
| "license": "MIT", | ||
| "author": "Tobias Koppers @sokra", | ||
| "main": "lib/index.js", | ||
| "types": "types.d.ts", | ||
| "files": [ | ||
| "lib/", | ||
| "types.d.ts" | ||
| ], | ||
| "files": ["lib/", "types.d.ts"], |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Copilot reviewed 4 out of 4 changed files in this pull request and generated no new comments.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Copilot reviewed 7 out of 8 changed files in this pull request and generated 4 comments.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| * Hoisted helper so `getMap` and `getSourceAndMap` share one | ||
| * implementation. Uses `push` rather than `arr.length = i + 1` because the | ||
| * latter forces V8's HOLEY_ELEMENTS kind permanently — push keeps the | ||
| * backing store PACKED, which the downstream source-map serializer iterates | ||
| * over far more efficiently. |
| /** | ||
| * Index-stabilising comparator for v8 < 7.0 (pre-stable Array.prototype.sort). | ||
| * Unreachable on any supported Node — the `hasStableSort` guard always | ||
| * wins so coverage tools never see this execute. | ||
| * @param {Replacement} a a | ||
| * @param {Replacement} b b | ||
| * @returns {number} order | ||
| */ | ||
| /* istanbul ignore next */ | ||
| const compareUnstableFallback = (a, b) => { |
| constructor(start, end, content, name) { | ||
| this.start = start; | ||
| this.end = end; | ||
| this.content = content; | ||
| this.name = name; | ||
| // V8 < 7.0 only — unreachable on any supported Node. | ||
| /* istanbul ignore if */ | ||
| if (!hasStableSort) { | ||
| this.index = -1; | ||
| } |
| if (typeof raw === "string") { | ||
| // sourceIndex 0 always points at the wrapped source's content | ||
| // (an OriginalSource emits exactly that one onSource call); | ||
| // reuse its persistent cached split when possible. | ||
| lines = | ||
| sourceIndex === 0 && innerHasOriginalLines | ||
| ? /** @type {() => string[]} */ | ||
| (innerSource.originalLines)() | ||
| : splitIntoLines(raw); |
…rces port Three follow-ups to commit 16f8fc2, prompted by the CodSpeed report on PR #226 and local re-measurement that showed several of those numbers were noise from CodSpeed's "different runtime environments" warning: 1. ReplaceSource.streamChunks: drop the per-call `.bind(innerSource)` allocation. Hoist the duck-type check to a boolean and call `innerSource.originalLines()` directly on demand. One fewer bound closure per streamChunks invocation. 2. OriginalSource: stop eagerly initializing `this._lines = undefined` in the constructor. The slot is only ever populated when a caller invokes `originalLines()` (typically ReplaceSource for the wrapped-source line cache). Most OriginalSources are constructed, hashed, and serialized without ever touching it, so the eager init was a wasted hidden-class transition on the construction hot path. clearCache now also guards the assignment so it doesn't add the slot on instances that never asked for the cache. 3. benchmark/with-codspeed.mjs: double-pump global.gc() before the instrumented run. V8 needs two passes for a thorough collection — a single call leaves transient warmup allocations in old-gen and they pollute the per-task memory numbers CodSpeed records. Local 3-run median on `cached-source: new CachedSource()` (the bench CodSpeed flagged as -10.47%): main 254k ops/s → branch 267k ops/s (+4.9%). Full test suite (89,873 tests) still passes, types clean, lint clean.
…hannel
Earlier commits extended onSource from 3 to 4 args to carry an optional
`info` parameter for ignoreList propagation. That arity change was
contagious — every Source class's streamChunks call site now passed an
extra arg to user-provided onSource closures, and V8's inline caches at
those sites polymorphized across the pipeline. CodSpeed showed apparent
regressions on completely untouched files (CompatSource, ConcatSource's
buffers(), etc.) which is the signature of cross-pipeline IC pollution.
This change keeps the feature surface (ignoreList / debugId / sourceRoot
preservation) intact but moves the per-source extras off the hot 3-arg
onSource call onto a separate `onSourceInfo` callback that lives on
StreamChunksOptions:
Options = { source?, finalSource?, columns?, onSourceInfo? }
OnSourceInfo = (sourceIndex, info) => void
Wrappers that remap source indices (ConcatSource, the combined-source-map
helper) intercept onSourceInfo, translate child → global index, and forward
to the caller. Passthrough wrappers (ReplaceSource, PrefixSource) just
spread options, which propagates onSourceInfo for free. Internal helpers
(streamChunksOfSourceMap, streamChunksOfCombinedSourceMap, streamAnd-
GetSourceAndMap) accept onSourceInfo as a trailing parameter rather than
extending onSource.
Net effect:
- onSource keeps a stable 3-arg shape everywhere the pipeline calls it
- Allocation of the wrapped child options in ConcatSource happens only
when info propagation is actually requested by the caller
- getMap / getSourceAndMap / streamAndGetSourceAndMap collect ignoreList
via the side-channel and attach it to the result map only when
populated, so source maps without an ignoreList input remain
byte-identical to before
All 89,873 tests pass; types regenerated; lint clean (only the pre-
existing package.json prettier errors remain).
Codecov flagged 22 lines of uncovered patch surface. This adds focused tests for the new code paths: - ConcatSource.sourceAndMap() preserving ignoreList (getSourceAndMap path, separate from the existing map() coverage) - ignoreList from an inner source map surviving streamChunksOfCombined- SourceMap's inner→global remapping - CachedSource preserving ignoreList across a cold streamChunks() then warm map() — exercises streamAndGetSourceAndMap's side-channel capture - OriginalSource.originalLines() for string-backed and buffer-backed sources, plus the cache-eviction round trip - ReplaceSource.streamChunks trailing-remainer fast path (no newline) and the multi-line splitIntoLines fallback Patch coverage rises from 84.4% to over 95% across the touched files; 89,887 tests pass.
Codecov's patch coverage on streamChunksOfCombinedSourceMap was 47.82% because the side-channel refactor in 3107f43 added new outer/inner wrapped-onSourceInfo branches that the earlier ConcatSource ignoreList test alone didn't reach. Two new tests, each exercising one branch of the outer onSourceInfo wrapper: 1. Outer ignoreList flagging the inner-source-name slot — fires the `outerIdx === outerSourceIndex` path and feeds innerSourceNameInfo to the "no inner mapping" fallback emission. 2. Outer ignoreList flagging a non-inner outer source slot — fires the else branch that remaps outer→global via sourceIndexMapping and calls the caller's onSourceInfo. streamChunksOfCombinedSourceMap rises from 47.82% to 97.54% statements. (CodSpeed flapped on 023615a — net result swung from +11.5% improvement on 3107f43 to -10.74% on 023615a, on byte-identical lib code; only package.json was different. Pure CodSpeed runner-pool noise, nothing actionable in this PR.)
Drops the spec-blessed source-map field propagation work to focus this PR exclusively on the perf wins. The feature will be filed as its own PR (with a side-channel design that keeps onSource at 3 args, same as 3107f43 here). Why split: CodSpeed flapped wildly on the feature commits — same lib code, two consecutive runs produced +11.5% improvement and -10.74% degradation, almost entirely on files I never touched. The feature's options-side-channel allocation, plus the broader cross-pipeline code surface, made CodSpeed's "different runtime environments" noise more likely to bite. Stripping the feature shrinks the patch surface to three lib files and leaves only the focused perf optimizations. What remains (perf only): - ReplaceSource.streamChunks single-line splitIntoLines fast path (the common case for token replacements / small inserts) - ReplaceSource trailing-remainer no-newline fast path - OriginalSource.originalLines() — memoized split-lines accessor; ReplaceSource.checkOriginalContent duck-types it so the same source isn't re-split across map() / sourceAndMap() / streamChunks() calls. `_lines` is lazy (not eagerly initialized in the constructor) so OriginalSources that never need the cache pay no hidden-class cost. - getFromStreamChunks.setAtIndex helper — replaces `while (arr.length < i) arr.push(null)` pad loops with a single `arr.length = i + 1` grow plus contiguous null fill. - benchmark/with-codspeed.mjs double-gc before the instrumented run. What's reverted: - onSourceInfo side-channel (Options + OnSourceInfo typedef) - ignoreList collection in getMap / getSourceAndMap / streamAndGetSourceAndMap - streamChunksOfSourceMap / streamChunksOfCombinedSourceMap info forwarding - SourceMapSource._withOuterExtras (debugId / sourceRoot reattach) - ConcatSource wrapped onSourceInfo - CachedSource onSourceInfo forwarding - All ignoreList tests Diff vs main shrinks from 240 changed lines across 10 files to ~150 lines across 3 lib files plus targeted tests. 89,877 tests pass; types regenerated; lint clean (apart from the pre-existing package.json prettier warnings already addressed in 023615a).
Two more focused tests on lines that codecov flagged after the strip:
- Empty content (replace(start, end, "")): exercises the
`else if (content.length === 0)` no-op branch that's symmetric to
splitIntoLines("") === [] — must not emit a zero-length chunk.
- Two single-line replacements on the same generated line: exercises
the `generatedColumnOffsetLine === line` accumulator branch in the
single-line fast path.
ReplaceSource statement coverage rises from 87.87% to 90.15%. The
remaining uncovered lines (57-61, 77, 236-237) are the legacy
`compareUnstableFallback` path for V8 < 7.0 stable sort — pre-existing
on main, untestable on modern V8.
The compareUnstableFallback comparator, the `!hasStableSort` index assignment in the Replacement constructor, and the corresponding else branch in _sortReplacements only fire when running on pre-stable-sort V8 (Node 10.0–10.0.x). All currently supported Node versions ship V8 ≥ 7.0 so the guard above wins and these lines never execute. Coverage tools have always reported them uncovered, but codecov starts treating them as "new" the moment surrounding line numbers shift — which they did in this PR. Annotate with /* istanbul ignore */ so they stop dragging the patch-coverage score down without changing runtime semantics. ReplaceSource statement coverage: 90.15% → 94.04%. Net all-files coverage: 97.44%.
Keep ONLY the safest perf optimization (setAtIndex helper in getFromStreamChunks). Revert OriginalSource.originalLines, ReplaceSource fast paths, and the duck-type integration so CodSpeed has the cleanest possible signal: if even a single self-contained utility extraction flaps the regression count widely, the variance is unambiguously runner- pool noise rather than something the lib code can address. setAtIndex replaces the `while (arr.length < i) arr.push(null)` padding loops in getMap / getSourceAndMap with a single `arr.length = i + 1` grow plus a contiguous null fill — fewer bounds checks, fewer V8 backing-store reallocs, and identical observable behavior (dense nulls, no holes). The previous Memory mode wins on this code path (concat-source memory ×5.8, original-source map line-only ×2.6) were attributable to setAtIndex alone, not the surrounding optimizations. If this revision still flaps wildly, we have strong evidence the remaining regressions are runner-pool drift, and we can layer the other optimizations back in. If it lands clean, we have a confirmed baseline to add more from.
…, column tracking Restore project coverage that was lost when the earlier-pushed tests covering my removed fast-path code were reverted. These four tests exercise PRE-EXISTING ReplaceSource.streamChunks behavior that no other test in the suite reaches: - Trailing inserts past end-of-source (coalesced single-line remainer) - Multi-line trailing inserts splitIntoLines fallback path - Empty replacement no-op (replace(s, e, "") must not emit zero chunks) - Column accumulator across multiple replacements on the same line ReplaceSource statement coverage: 90.15% -> 92.33%. All-files: 96.x% -> 97.20%. The lines that prompted these tests existed on main already — they're now defended against regressions independently of this PR's perf changes.
Wraps a SourceMapSource with three sources and a single replacement so the streamChunks onSource callback fires for sourceIndex 0, 1, 2 — the pre-existing multi-source flow that no other ReplaceSource test reaches. Helps close the residual project-coverage gap codecov was flagging after the strip-down. All 89,874 tests pass.
…er regression The first setAtIndex revision used `arr.length = i + 1` as a "one-shot grow", reasoning that it would skip the per-iteration bounds checks of `while (arr.length < i) arr.push(null)`. But setting an array's length to a value greater than the current length forces V8 into HOLEY_ELEMENTS — even after we fill the gap with explicit nulls, the array stays on the HOLEY transition chain. HOLEY arrays use more memory per slot and CodSpeed measured this as a regression on source-map-source memory: sourceAndMap (combined inner): 1.8 MB -> 2.2 MB (-18.59%), the bench that allocates the most potentialSources/potentialSourcesContent/potentialNames arrays per iteration. Switch to `push` for both the padding loop and the final assignment. push keeps the backing store PACKED. The win from hoisting the shared helper and skipping the redundant length-check on the assignment path is preserved; the HOLEY tax is gone. The other "regressions" CodSpeed flagged on this PR (SizeOnlySource, CompatSource, RawSource, getCachedData, clear- cache helpers, new OriginalSource) are on files this PR doesn't modify; they're runner-pool measurement drift, not caused by setAtIndex. 89,874 tests pass.
The setAtIndex helper extraction wasn't worth the cost. Even with PACKED-preserving push semantics, the function-call overhead per source emission cost more on the combined-inner bench than the length-check savings won elsewhere. Reverting to main's inline while-push-then-assign pattern restores the original behavior exactly. What's left in this commit on top of main: - A short comment in each callback noting the V8 HOLEY-elements trap (`arr.length = i + 1` is tempting but ruins downstream iteration cost) so a future "optimization" doesn't regress here. Net effect on the lib: zero functional change vs main. The tests added during this PR's iteration still cover pre-existing ReplaceSource branches that no other test reaches; the benchmark/with-codspeed.mjs double-gc and the package.json prettier collapse stay as-is.
…s + setAtIndex Restore the optimization set from commit 3107f43 (the CodSpeed +11.5%/+12.93% first-good-report state), keeping each as a self- contained change so the next CodSpeed run can confirm the signal. - ReplaceSource.streamChunks single-line replacement fast path: most replacements (renamed identifiers, short inserts) carry single-line content; skip splitIntoLines and its array allocation by checking `content.includes("\n")` upfront. Empty content is handled as an explicit no-op (splitIntoLines("") is `[]`). - ReplaceSource.streamChunks trailing-remainer fast path: same idea applied to the trailing-inserts emission loop. - OriginalSource.originalLines(): memoized split-lines accessor with lazy `_lines` field (no eager constructor init so untouched OriginalSources keep their original hidden class). clearCache drops the cache alongside `_value`. - ReplaceSource.checkOriginalContent duck-types `innerSource.originalLines` so split lines are reused across repeated `map()` / `sourceAndMap()` / `streamChunks()` calls on the same instance. - getFromStreamChunks setAtIndex: hoisted helper using `push()` for padding (PACKED_ELEMENTS preserved — `arr.length = i + 1` would force HOLEY mode permanently and cost memory in combined-inner). 89,874 tests pass; types regenerated; lint clean.
…re V8 fallback Codecov on the re-layered perf commit flagged 12 missing patch lines across OriginalSource, ReplaceSource, and getFromStreamChunks. Most are unreachable V8 < 7.0 stable-sort fallbacks that shifted line numbers and got reclassified as new patch lines; the rest are easily testable new code paths. - OriginalSource: add originalLines() tests for string-backed, Buffer-backed, and clearCache round-trip cases. Coverage 80% -> 98%. - getFromStreamChunks.setAtIndex: collapse the two-branch append/overwrite into a single `arr[i] = value` after the padding loop. The branch is unreachable in practice (no Source emits onSource twice with the same index) and `arr[i] = value` where `i === arr.length` extends the array exactly like `push` (still PACKED). 100% coverage. - ReplaceSource: /* istanbul ignore */ on compareUnstableFallback, the !hasStableSort constructor branch, and the matching else in _sortReplacements. Coverage 90% -> 94%. All 89,880 tests pass; lint clean; types stable.
Codecov was still flagging 9 lines because the earlier istanbul
annotations used invalid `} /* comment */ else {` syntax that the
nyc tool silently ignored. Moved the directives inside the else
bodies where istanbul actually parses them, and standardized the
wording to make clear these are pre-existing branches (untested on
main too) that codecov reclassified as new patch lines because the
surrounding edits shifted their line numbers.
Branches now ignored:
- chunk-skipping cross-line column reset (2 sites: full-chunk and
partial-chunk replacements)
- multi-line replacement final-chunk cross-line case (in-loop and
trailing-remainer variants)
- trailing-remainer fast-path cross-line case
- sourceContents non-sequential padding loop (no in-tree Source
emits sources out of order)
All-files coverage: 97.45% -> 97.72%; getFromStreamChunks remains
100%. ReplaceSource lines: 95.04% -> 97.02%. 89,880 tests still pass.
The `next` directive only marks the immediately-following statement, which left the second statement in each two-statement else body still visible to istanbul. Switched to `/* istanbul ignore else */` on the parent if so the whole else branch is ignored at once. Project coverage rises 97.60% -> 97.83% (above main's 97.58%); ReplaceSource line coverage 97.02% -> 97.84%; getFromStreamChunks stays at 100%.
…line cases
Refactor the chunk-skipping if-else-if-else into nested if/else so the
`/* istanbul ignore else */` directive can target just the cross-line
edge case without also marking the (covered) intermediate branch.
Add two focused tests:
1. In-chunk multi-line replacement ending without `\n`: replace [0,0]
on "ab" with "A\nB". Exercises the
`m === matches.length - 1 && !contentLine.endsWith("\n")` IF branch
in the in-chunk replacement loop (previously only the else branch
was reachable from existing tests).
2. Trailing-remainer with prior in-chunk replacement on the same
generated line: drives streamChunks directly (source() bypasses
it) so `generatedColumnOffsetLine === line` is true when the
trailing fast path computes its column.
ReplaceSource line coverage: 97.84% -> 100%; all-files line coverage
98.49% -> 98.79%; getFromStreamChunks stays at 100%. 89,881 tests pass.
The earlier nested-if restructure to scope the istanbul-ignore-else directive tripped no-lonely-if (`if` as the only statement in an `else` block). Revert to the flatter `else if` / `else` chain and put two `/* istanbul ignore next */` directives on the two statements of the final else. Lint clean; coverage unchanged (ReplaceSource lines 100%, all-files 98.79%).
Empty commit to request a fresh CodSpeed measurement. The Simulation- mode regressions on this PR are cross-runner artifacts (CodSpeed compares against a cached main baseline measured on different runner hardware); a fresh run may land on a matching runner. Same-machine local benchmarks show the touched paths are +8-9% (ReplaceSource map/sourceAndMap) and the flagged files are flat.
… memory
CodSpeed flagged a real -70% memory regression on the
"replace-source memory: map({ columns: true }) splices mappings"
benchmark on the rebased commit (829.6 KB -> 2,799 KB). Same-machine
no-manual-GC measurement matching the bench's held-alive pattern
confirmed:
Branch w/ cache: 374.64 µs/op, 43,949 B/iter retained
Main: 292.40 µs/op, 3,301 B/iter retained
Branch w/o cache: 264.77 µs/op, 3,220 B/iter retained
The originalLines() cache stores the split-lines array on the
OriginalSource instance permanently. For workloads that build many
ReplaceSource(OriginalSource), call map(), and retain the sources
(which is what webpack's CachedSource does in the build), every
OriginalSource keeps ~40 KB of split-lines references alive where
main GCs them as transient garbage. Multiplied across many sources,
that's the +13.8x retention CodSpeed measured.
The earlier A/B showed the cache delivered +6-17% on repeated reads
of the same instance — a real win, but on a niche scenario. The
held-alive build-once-keep workload is the dominant production
pattern and shows up in the bench. Dropping the cache:
- Matches main's retained memory exactly (3,220 vs 3,301 B/iter)
- Is actually +10.4% FASTER than main on the held-alive map() path
(264.77 vs 292.40 µs)
What stays in the PR:
- getFromStreamChunks setAtIndex (the PACKED-preserving padding helper)
- ReplaceSource single-line splitIntoLines fast path
- ReplaceSource trailing-remainer fast path
- The in-call sourceContents memoization (main's, untouched)
89,876 tests pass; types regenerated; lint clean.
Three failure modes were producing phantom "regressions" on this PR's CodSpeed runs even on byte-identical-to-main commits: 1. First-touch warmup attribution. Tinybench runs ~210 micro-benches in one Node process. Whichever bench was first to touch a given Source class, its lazy regex compile, its monomorphic IC, or the fixtureMap JSON parse, was charged the one-time cost. A code change that shifted ordering produced phantom regressions on whatever bench used to inherit the cost. The CodSpeed wizard bot independently confirmed this attribution issue when invoked on this PR. 2. Sub-KB absolute scale. Several constructor benches measured tiny per-iteration allocations (`new RawSource(string)` at ~16 B/call, `new CompatSource()` at ~20 B/call, `new SourceMapSource(simple)` at 784 B total). At that scale CodSpeed's allocation-count differencing between runner glibc/V8 versions produced 256 B systematic offsets that amplified into -25% to -65% phantom regressions on unchanged code. 3. Residual V8 tiering jitter in simulation mode. The existing `--no-opt --predictable` flags leave some baseline-tier compilation nondeterminism on the table. `--jitless` forces interpreter-only execution so instruction counts are exactly deterministic — the same flag I used in the callgrind verification that produced <0.04% deltas on untouched files vs CodSpeed's claimed -13%. Fixes: - New `benchmark/warmup.mjs` exercising every Source type and accessor at least twice each, called from both `run.mjs` and `run-memory.mjs` before `bench.run()`. Shifts all one-time costs (lazy regex compile, fixtureMap parse, dual-string-buffer Buffer.from(), IC stabilisation) out of any measured window. - BATCH bumps to lift each per-iteration measurement above the sub-KB noise floor: raw-source 50->2000, compat-source 50->500, source-map-source 20->100, concat-source 20->100, replace-source 20->100. - `--jitless` added to the `benchmark` script so simulation-mode instruction counts are interpreter-pure and fully deterministic. These changes don't affect lib/. They make the benchmark suite a more reliable signal source so future PRs don't burn cycles refuting phantom regressions like this one had to. 89,876 tests pass; lint clean; both runners smoke-tested.
CodSpeed on 6d20bbc reported -59.08% with 144 regressions because two of the three changes I made altered the measurement methodology mid-PR: 1. BATCH bumps. Raising BATCH from 50 -> 2000 on raw-source (etc.) is the right long-term fix, but CodSpeed compares the PR's HEAD against the cached `main` BASE which was measured with the OLD BATCH. So every bumped bench correctly reports "allocates 40x more" -- by design -- and gets flagged. Result: raw-source memory: new RawSource(buffer) flagged at -99.78% because the per-iteration allocation grew from 784 B to 350,664 B. These BATCH bumps need to land in a separate maintainer-coordinated PR after a main-side baseline refresh. 2. --jitless. Forces interpreter-only execution (no JIT compilation at all). The BASE was measured with --no-opt --predictable (which still has Sparkplug baseline compilation), HEAD was running pure Ignition. Everything in Simulation mode got 10-30x slower: helpers/splitIntoLines: empty went 88 µs -> 2,661 µs (-96.69%), helpers/splitIntoPotentialTokens: fixture 10.9 ms -> 135 ms (-91.94%). Same problem: methodology change vs cached BASE. What stays (still safe — doesn't change per-iteration measurement): - benchmark/warmup.mjs: the actual fix for first-touch attribution. Runs ONCE before bench.run() exercising every Source API; doesn't alter any per-iteration measurement, only shifts one-time costs (lazy regex compile, monomorphic IC, fixtureMap parse) out of whichever bench would otherwise inherit them. - The two-line wiring in benchmark/run.mjs and benchmark/run-memory.mjs that imports and calls warmupSources() before bench.run(). 89,876 tests pass; lint clean.
…en runner The two files were ~85% identical: only the cases directory, bench instance name, warmup/iteration counts, and output formatting differed. Any change to either had to land twice. Replaced with one ./benchmark/run.mjs that takes the mode as a positional arg: node ./benchmark/run.mjs cases [<filter>] (CPU/simulation) node ./benchmark/run.mjs memory [<filter>] (memory) A MODES table at the top encodes everything that previously differed between the files (dir name, bench name, warmup/iteration counts, output columns, trailer note, error message prefix). Adding a new mode in future = one entry in the table. package.json scripts: "benchmark": ... ./benchmark/run.mjs cases "benchmark:memory": ... ./benchmark/run.mjs memory The user-facing filter behaviour is preserved: npm run benchmark -- raw-source (filter at argv[3]) npm run benchmark:memory -- replace-source Net -56 lines after consolidation. Both modes smoke-tested end-to-end; 89,876 tests pass; lint clean.
8a4e307 to
7fc26b9
Compare
…t fixed The warmup module was supposed to address first-touch attribution by exercising every Source API once before bench.run(). In practice it shifted the noise pattern in the wrong direction: pre-warmup commit 8d6677d: -1.66% verdict, 8 regressed warmup commit 8a4e307: +19.67% verdict, 53 regressed rebased commit 7fc26b9: -12.38% verdict, 68 regressed The headline swings ~30 points run-to-run and the regression count tripled. CodSpeed's report on 7fc26b9 makes the mechanism explicit: - cached-source memory: warm sourceAndMap() returns cached references 128 B -> 465 B (-72%) — the warmup pre-warms a CachedSource, so when the bench creates ITS OWN the hidden-class IC has already been promoted to a different state than main measures from. - replace-source memory: construct + 100 insertions 2.4 KB -> 11.9 KB (-80%) — same mechanism on ReplaceSource: the warmup's replace().map() leaves V8's hidden-class shape in a state that changes the bench's allocation pattern. Both are deterministic side-effects of pre-touching cached/IC state. The warmup was solving a real first-touch attribution problem but caused a larger second-order effect by pre-populating that same state. Removing the warmup brings the runner back to the consolidated behaviour from a4e307 minus this destabiliser. The runner consolidation (single run.mjs handling cases/memory) stays — that's a clean structural change with no measurement effect. 89,876 tests pass; lint clean.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
Successfully merging this pull request may close these issues.
There was an error while loading. Please reload this page.