Skip to content

Discard tokens unique to one side before running the Myers loop - #744

Open
yuluod wants to merge 11 commits into
kpdecker:masterfrom
yuluod:perf/discard-unique-tokens
Open

yuluod wants to merge 11 commits into
kpdecker:masterfrom
yuluod:perf/discard-unique-tokens

Conversation

@yuluod

@yuluod yuluod commented Nov 11, 2026 •

Copy link
Copy Markdown

Implements the optimisation sketched at the end of #736 (comment), on top of #732. Addresses the performance half of #720.

Idea

A token that occurs (after normalization) on only one side can never be matched - every common subsequence consists solely of tokens occurring on both sides. So before the Myers loop runs, tokens whose value has zero occurrences on the other side are dropped; the loop then runs on the remaining skeleton, and the dropped tokens are reinstated as pure deletions/insertions afterwards. This shrinks both N and D of the O(ND) loop to the shared tokens, and is the same discard step GNU diff and git's xdiff perform. Unlike the rejected all-or-nothing shortcut in #736, performance degrades smoothly with the overlap ratio - the "99999 unique lines + 1 shared line" case discussed there is exactly what this fixes.

Detection and reinstatement are O(n); occurrence counting keys on the normalizeToken() output introduced by #732, so all equality options work unchanged.

Correctness

The reinstatement works on the component array, before buildValues slices the original token arrays. Two facts make byte-identical output achievable:

  • Within a run of edits between two equal components, the algorithm always emits all removals before all insertions, merged into at most one removal and one insertion component - the output contract since Prefer to order deletions before insertions when the edit cost is the same, like the Myers diff paper does #439, visible in addToPath and the main loop's tie-breaking. A run is therefore fully described by two counts, and the skeleton's own edit order within a run never needs to be preserved.
  • Each run corresponds to one contiguous slice of the old array and one of the new array, so buildValues reconstructs values from the counts alone. Equal components are split wherever dropped tokens are wedged between their matched tokens.

maxEditLength semantics are preserved: the dropped tokens' count is subtracted from the limit the main loop runs against (they cost one edit each regardless of what the loop finds), and if they alone exceed the limit the diff aborts immediately.

Guards

The optimisation is skipped (plain algorithm runs, output trivially unchanged) when:

  • a comparator is passed (equality semantics unknown, so equal tokens may have different normalized values),
  • equals is overridden by a subclass (same problem),
  • any normalized token is not a string (a Set would treat NaN as occurring on both sides, unlike the === that equals uses).

Verification

  • Full test suite passes (346/346). One async-mode test now uses inputs that don't trigger the optimisation, since its original inputs ('ax'.repeat(1000) vs 'ay'.repeat(1000)) collapse to an identical skeleton and complete instantly instead of yielding across many iterations - which is the optimisation working as intended.
  • Fuzzed against the base commit: 12,000 cases (four seeds) across all diff functions × option combinations incl. oneChangePerToken, maxEditLength, timeout, newlineIsToken, stripTrailingCr; string pools spanning zero/high overlap; empty/whitespace-only inputs. Zero output differences.
  • Exhaustive maxEditLength sweep: every limit from 0 to 30 over 91 inputs, sync and async, aborts on exactly the same values as the base commit.
  • 200k-token inputs with oneChangePerToken (the largest component arrays this PR produces) run without error and match the base commit.
  • The only observable behaviour change: some diffs that previously hit a timeout now finish within it (38 of 6,000 fuzz cases).

Benchmarks

Median of 5 runs, Node 26, Apple Silicon, base (2c99d8c) vs this PR after the review rework (Sets, no discard-size threshold, buildValues taking the component array directly):

Case base PR (after review)
diffChars 8000×8000, zero overlap 941.5 ms 0.55 ms
diffChars 8000×8000, ~50% shared 863.7 ms 1.2 ms
diffLines 6000 lines, 1% shared 686.9 ms 1.85 ms
diffLines 6000 lines, 10% shared 639.5 ms 1.75 ms
diffLines 6000 lines, 50% shared 367.5 ms 2.2 ms
diffLines 6000 lines, realistic small edit 0.80 ms 1.3 ms

The realistic small-edit case is the cost of the O(n) occurrence scan (which GNU diff and git also pay); it is ~+0.4 ms absolute on 12,000 tokens. The discard pass always runs when the guards pass: benchmarks showed a discard-size threshold bought nothing, because the Map counting it required cost more than the skeleton work it saved.

A token that occurs (after normalization) on only one side can never be
matched, so drop such tokens up front, run the O(ND) loop on the
remaining skeleton, and reinstate the dropped tokens as pure
deletions/insertions - the discard optimisation used by GNU diff and
git's xdiff. Byte-identical output to master, verified by fuzzing across
all diff functions and option combinations.

@oBusk oBusk 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.

I had a look at this out of curiosity!

One thing that should be brought up is that xdiff and GNU diff starts by discarding shared prefix/suffix, i.e. all elements that are identical from top to first diff, and from bottom to last diff. That would make the counting pass a lot cheaper on mostly-identical inputs, since it'd only look at the part that actually changed.

Additionally, I have two questions, see the code comments, and also wanted to mention that yarn eslint is failing atm.

Comment thread src/diff/base.ts Outdated
const skNorm: TokenT[] = [];
const skToOrig: number[] = [];
for (let i = 0; i < tokens.length; i++) {
if ((otherCounts.get(normalized[i] as string) ?? 0) > 0) {

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.

Arrays are typed TokenT[], but then values are cast to string throughout?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in 1d536bd - the string-only guard in buildDiscardPlan now does a single oldNormalized as string[] cast, and the plan's token arrays are typed string[] from there on, so the scattered as string casts are gone. The one remaining cast is at the wiring site, where the plan's normalized arrays are handed back to the loop as TokenT[] (the loop consumes them like any other normalized array).

Comment thread src/diff/base.ts Outdated
Comment on lines +449 to +450
oldSk: oldS.sk,
newSk: newS.sk,

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.

Do we ever read values out of these arrays, I can only find .length? If so, would just a counter be more efficient?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Good catch - they were dead weight. Dropped in 1d536bd: the plan now only carries the skeleton length implicitly via oldSkToOrig.length, the normalized skeleton arrays the loop actually compares, and the index maps; buildValues slices the original token arrays as before. That also saves two pointer arrays per diff.

- Trim the maximal common prefix before counting so mostly-shared inputs
  only pay for the part that changed. The common suffix deliberately
  stays: the unoptimised algorithm's final equal run is whatever its
  alignment matches last, which is not always the maximal suffix, so
  trimming it would change which minimal edit script gets picked.
- Drop the skeleton token arrays (only their lengths were read) and
  type plan tokens as strings after the guard.
- Fix eslint (curly, func-style, no-undef-init).
@yuluod

yuluod commented Nov 12, 2026

Copy link
Copy Markdown
Author

Thanks for the review @oBusk! All three points addressed in 1d536bd:

Prefix trim - yes; suffix trim - turns out to be unsafe for byte-identical output. I implemented the shared prefix trim (the loop and the counting pass now only look at the part after it). The suffix I had to leave alone, and I want to flag why since it's a real difference from xdiff/GNU diff: jsdiff's output must stay byte-identical to what the current algorithm picks, and the algorithm's final equal run is whatever its chosen alignment happens to match last - which is not always the maximal common suffix. Concrete case (from the test suite): diffing ['foo', '\r\n', 'bar'] against ['foo', ' ', '\r\n', '\r\n', '\r\n', 'bar'] in word mode, the algorithm matches the old '\r\n' against the middle of the inserted run and emits [ins ' '][eq '\r\n'][ins '\r\n\r\n'] - it deliberately does not match the trailing '\r\n' of the maximal suffix. Forcing the suffix to the ends produces a different (still minimal) script, changing the output. The prefix has no such problem: the seed path consumes the maximal common prefix greedily by construction, so cutting it is exactly equivalent. The prefix is also where most of the win is for the mostly-identical case, since it's cut before the counting pass runs.

Dead skeleton arrays - you were right, only .length was ever read. Dropped; the plan now carries just the normalized skeleton arrays the loop compares, the index maps, and counts.

Types - single as string[] cast behind the string-only guard now; plan fields are string[].

eslint - fixed (curly, func-style, no-undef-init).

After the changes: 346/346 tests, re-fuzzed against master (9,500 cases across all diff functions × option combinations) with zero output differences, and benchmarks hold (zero-overlap diffChars ~2180x, 1%-shared diffLines ~450x, mid-overlap ~11x; the realistic-small-edit case remains ~+2 ms for the counting pre-pass, which is the same trade GNU diff makes).

Comment thread src/diff/base.ts Outdated
Comment on lines +195 to +196
// A token that occurs (post-normalization) on only one side can never be matched, since a
// common subsequence consists solely of tokens occurring on both sides. Cutting the common

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Simpler: "A token that occurs (post-normalization) on only one side must be an insertion or deletion."

@yuluod yuluod Dec 1, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done - much better, adopted.

Comment thread src/diff/base.ts Outdated
Comment on lines +196 to +199
// common subsequence consists solely of tokens occurring on both sides. Cutting the common
// prefix/suffix and dropping such tokens before diffing leaves every possible match intact
// while shrinking the N and the D of the O(ND) Myers loop; trimmed and dropped tokens are
// reinstated afterwards. This is the optimisation used by GNU diff and by git's xdiff.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think sentence 2 here is likely to be a bit confusing in context to someone not already intimately familiar with the optimizations we're using here. It's perhaps non-obvious that it's describing two orthogonal optimizations, one of which was alluded to by the previous sentence and one of which is totally separate and unrelated.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

OH, wait, I get it - cutting the common PREFIX is actually not an optimization in and of itself (since the raw Myers algorithm will just consume the prefix in linear time anyway before doing any branching). It's only done to further optimize the bit where we remove tokens unique to one side.

(It's a bit confusing because removing a common SUFFIX really IS a potentially significant optimization when running the normal one-directional Myers algorithm!)

@yuluod yuluod Dec 1, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

You read it exactly right, and the comment was hiding that. Rewritten to keep the two things separate: the discard is the optimisation; cutting the common prefix only keeps the occurrence scan off the unchanged part (the unoptimised loop consumes a common prefix in linear time anyway, so the cut is not itself a speedup). It now also says explicitly that the common suffix is deliberately left in place, pointing at the rationale at the cut in buildDiscardPlan.

Comment thread src/diff/base.ts Outdated
* - `equals` is overridden by a subclass (same problem; note no built-in subclass overrides it,
* and subclasses that want this optimisation should override `normalizeToken` instead so that
* equal tokens normalize to the same string);
* - any token is not a string (Map keys compare by SameValueZero, so e.g. NaN would wrongly be

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Should be "any normalized token", I guess? I figure tokens don't strictly speaking need to stay the same type when normalized.

@yuluod yuluod Dec 1, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed ("any normalized token is not a string").

Comment thread src/diff/base.ts Outdated

/**
* Bookkeeping for the "trim common prefix/suffix + discard unique tokens" optimisation (see
* buildDiscardPlan). The maximal common prefix and suffix are cut off before anything else, so

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

As with a bunch of other places, the comment here suggests we trim the common SUFFIX too, but in fact we don't.

@yuluod yuluod Dec 1, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed - this had slipped through in three places (the DiscardPlan doc, the done() comment and this one). All now say prefix-only, with the deliberate-suffix note pointing at buildDiscardPlan.

Comment thread src/diff/base.ts Outdated
Comment on lines +453 to +455
* When it can be applied but too little would be dropped for it to pay off, a trim-only plan
* (with no `discard` section) is returned; the caller then runs the loop on the mere middle
* section.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Is there any point? The algorithm will immediately consume the common prefix without branching anyway, so trimming the common prefix before running the algo isn't really an optimization at all.

(Trimming the common suffix IS an optimization, at least in the one-directional version of the Myers algorithm we use in jsdiff (though not in the two-directional version where the algorithm builds one snake from each side until they cross in the middle). But we don't do that.)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Ah, I guess we've already found the common prefix before we discover it's not worth doing the optimization, so this is just avoiding having to iterate over the common prefix a second time for no reason?

@yuluod yuluod Dec 1, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Removed entirely - you were right that it wasn't pulling its weight (numbers in my reply on the threshold comment). There is no trim-only plan shape anymore: a plan either exists (and always carries a discard section) or the guards failed and the plain algorithm runs on the untouched arrays - which also removes a pointless full-array slice(0) copy that used to happen on the guard-failure path.

Comment thread src/diff/base.ts Outdated
Comment on lines +490 to +492
// is not necessarily the maximal common suffix (e.g. diffing ['foo','\r\n','bar'] against
// ['foo',' ','\r\n','\r\n','\r\n','bar'] in word mode, it matches the old '\r\n' against the
// middle of the inserted run rather than the trailing one, and inserts it), so forcing the

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Confusing example because it's not immediately obvious (even to me!) how these texts break down into tokens in word mode. Ideally the example would be a diffChars example that uses nothing but alphabetical characters.

@yuluod yuluod Dec 1, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Replaced with a pure-alphabet one: diffChars('aa', 'ba') produces [ins 'b'][eq 'a'][del 'a'] - the algorithm matches the old leading 'a' against the new trailing 'a' and deletes the old trailing 'a'. Cutting the maximal common suffix first would instead force [del 'a'][ins 'b'][eq 'a']. Both scripts are minimal, so forcing the suffix to the ends changes which minimal edit script gets picked. (Verified against master; the comment quotes exactly these two orderings.)

Comment thread src/diff/base.ts Outdated
Comment on lines +513 to +514
// side of the middle section (those, and only those, get dropped). On mostly-shared inputs
// (the common case) running on the skeleton would be pure overhead, so skip the skeleton

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Instead of building a skeleton, can we expose the set of unique-to-one-side tokens to the core algorithm, and have the algorithm check whether a token it encounters is in that set, and if so, instantly append an insertion or deletion change object to the diff but not adjust the diagonal or edit length accordingly?

And if this would indeed work, would it basically eliminate scenarios where it's not worth doing the optimization?

@yuluod yuluod Dec 1, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I looked into this seriously, but I don't think it can be made to work without giving up the byte-identical-output guarantee this PR is fuzz-verified against:

  1. Position bookkeeping. Skipping a unique token advances only one side, so newPos = oldPos - k stops holding - and extractCommon, the canAdd/canRemove bounds checks and the bestPath indexing all depend on it. Every Path would have to carry a physical newPos separate from the logical diagonal.
  2. Ordering. Appending the deletion the moment the token is encountered can place it after an insertion the unoptimised algorithm would have ordered before it. The removals-before-insertions-within-a-run contract (Prefer to order deletions before insertions when the edit cost is the same, like the Myers diff paper does #439) is exactly what expandDiscarded reproduces by construction, because it treats every edit run as one contiguous slice of each input. Fixing the ordering inside the loop means buffering and reordering components in the hot path - effectively expandDiscarded moved into the loop.
  3. Cost placement. The membership check would run inside the O(ND) loop (and inside extractCommon) for every diff, including ones with no unique tokens at all. Keeping the O(n) scan outside the loop leaves the common path untouched.
  4. It doesn't remove the scenario this comment targets. Knowing which tokens are unique still requires the O(n) pre-pass, so the fixed cost on mostly-shared inputs remains either way.

Comment thread src/diff/base.ts Outdated
Comment on lines +516 to +517
let discardedByOld = 0;
let discardedNew = 0;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

What's up with the asymmetry in the names, here? I think the meaning is symmetrical, but the names differ - "discarded by old" vs just "discarded new".

@yuluod yuluod Dec 1, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Gone with the Set rewrite below - the counts are derived from the skeleton lengths, there are no summation locals at all anymore.

Comment thread src/diff/base.ts Outdated
Comment on lines +499 to +500
const midOldEnd = oldNorm.length;
const midNewEnd = newNorm.length;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Clearer to just use oldNorm.length and newNorm.length directly rather than have these constants, no? (I'm guessing these were introduced at a time when common-suffix-trimming was on the cards.)

@yuluod yuluod Dec 1, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Removed - they were indeed leftovers from when suffix trimming was still on the cards.

Comment thread src/diff/base.ts Outdated
};
const midOldLen = midOldEnd - prefixLen;
const midNewLen = midNewEnd - prefixLen;
if (discardedByOld + discardedNew < (midOldLen + midNewLen) * 0.2) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Does turning off the optimization really save enough time to be worth the complexity and the extra work done checking whether to turn it off? If we just didn't bother with this, the code would be shorter, we'd skip all the summing of counts, and we wouldn't even need to use Maps at all; we could just use Sets of normalized tokens.

@yuluod yuluod Dec 1, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Agreed, and removed - but benchmarked rather than guessed, since this was the one place where the original design had data behind it. Same machine, same seeded inputs, median of 5 runs (ms, Node 26, Apple Silicon; base = the commit this PR branches from):

case base before (Map + 20% threshold) after (Sets, no threshold)
diffChars 8000x8000, zero overlap 941.5 0.60 0.55
diffChars 8000x8000, ~50% shared 863.7 4.06 3.99
diffLines 6000 lines, 1% shared 686.9 2.74 1.96
diffLines 6000 lines, 10% shared 639.5 2.59 2.51
diffLines 6000 lines, 50% shared 367.5 3.56 3.00
diffLines 6000 lines, realistic small edit 0.80 1.28 1.17

The punchline: Map get+set is two hash lookups per token and dominates the pre-pass by itself, so the Set version that always discards is never slower than Map+threshold on any case - including below-threshold inputs like the small-edit row, where it additionally pays the skeleton and reinstatement and still comes out ahead. The threshold, the trim-only plan shape, midOldEnd/midNewEnd and the discarded-count summation are all gone; the counts now fall out of the skeleton lengths. 9000 fuzz cases across all diff functions x option combinations remain byte-identical to master, 346/346 tests pass. If you'd still rather guard the mostly-shared case, the table says the guard buys roughly nothing - I'd rather keep the code simpler.

Comment thread src/diff/base.ts Outdated
* - Within one run of edits, the unoptimised algorithm always emits all removals before all
* insertions, merged into at most one removal and one insertion component (the loop's
* addToPath merges consecutive edits of the same kind, and its tie-breaking never places an
* insertion before a removal within a run - verified empirically across all diff functions

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Let's drop the "verified empirically across all diff functions and option combinations"; this is a documented fact (see release notes for #439) that can be confirmed by reading the code.

@yuluod yuluod Dec 1, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done - it now cites the #439 output contract instead of the empirical hedge.

Per review: the 20% discard threshold protected mostly-shared inputs from
the skeleton's overhead, but the Maps it counted into cost two hash
lookups per token - which dominates the pre-pass all by itself. With Sets
(one lookup per token) the always-discard version is never slower than
Map+threshold on any benchmarked case, including below-threshold inputs
where it additionally pays the skeleton and reinstatement and still wins:
diffLines 6000 lines 1% shared 2.74ms -> 1.96ms, 50% shared 3.56ms ->
3.00ms, realistic small edit 1.28ms -> 1.17ms (same machine, same seeded
inputs, median of 5; zero-overlap diffChars 8000x8000 stays ~1700x faster
than master). The threshold, the trim-only plan shape and the
discarded-count summation are gone; the discarded counts fall out of the
skeleton lengths, and the guard-failure path no longer makes a
full-array slice(0) copy.

Also per review: comments now say prefix-only everywhere (the suffix is
deliberately not cut, with a pure-alphabet example - diffChars('aa',
'ba') - proving why), the guards read "any normalized token", the prefix
cut is described as serving the occurrence scan rather than being a
speedup in itself, and the "verified empirically" hedge in
expandDiscarded is replaced by a reference to the kpdecker#439 output contract.

346/346 tests; 12000 fuzz cases across all diff functions x option
combinations remain byte-identical to master.
`components.push(...expanded)` and the `components.unshift(...)` prefix
reinstatement hit the engine's spread-call argument limit on large diffs:
a 200k-token `diffChars` with `oneChangePerToken` crashed with RangeError
where master returned fine (verified on both, plus a 200k-token common
prefix case). Build the reinstated prefix into its own array and walk
prefix + loop components separately when rebuilding the component list
for buildValues.

Also drop `DiscardPlan.oldLen`/`newLen`, which were written but never
read.

346/346 tests, eslint clean, 9000 fuzz cases across all diff functions x
option combinations remain byte-identical to master.
Comment thread src/diff/base.ts Outdated
Comment on lines +39 to +41
/** Always present in a returned plan: every plan that passes the guards drops the tokens
* unique to one side. */
discard?: {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

We're typing this as optional but commenting that it's "Always present". If it's always present, shouldn't we just make it non-optional and drop the comment?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

You're right - the optionality was a leftover from the trim-only plan shape that the Set rework removed. discard is now required, the comment is gone, and the plan?.discard checks collapse to plan.

Comment thread src/diff/base.ts Outdated
): ChangeObject<ValueT>[] | undefined {
const done = (value: ChangeObject<ValueT>[]) => {
const done = (lastComponent: DraftChangeObject | undefined) => {
// The loop produces components for the (possibly skeleton-of-the-) middle section only.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

"The loop" here seems unhelpfully ambiguous. I guess we mean something like "The main Myers algorithm loop, implemented below via repeated calls to execEditLength,"?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Agreed. It's now defined once in done as "the main Myers algorithm loop (implemented below via repeated calls to execEditLength)" and referred to as "the main loop" everywhere else this PR introduced the phrase.

Comment thread src/diff/base.ts Outdated
Comment on lines +117 to +177
const components: DraftChangeObject[] = [];
for (let component = lastComponent; component; component = component.previousComponent) {
components.push(component);
}
components.reverse();
if (plan?.discard) {
const discard = plan.discard;
const expanded = this.expandDiscarded(
components,
discard,
prefixLen, prefixLen, // Both sides start after the cut prefix.
oldTokens.length, newTokens.length,
options
);
components.length = 0;
// No spread call: `expanded` can hold one component per token, which is past the engine's
// spread-call argument limit on large inputs.
for (const component of expanded) {
components.push(component);
}
}
// Determine the components that reinstate the cut common prefix in front of the loop
// output. When the first loop component is also an equal run, the prefix merges into it:
// the unoptimised algorithm's greedy seed extractCommon consumes the prefix together with
// any matched tokens immediately following it as one maximal equal run. (With
// oneChangePerToken every token is its own component, so there is nothing to merge.)
const oneChangePerToken = !!options.oneChangePerToken;
const prefixComponents: DraftChangeObject[] = [];
if (prefixLen > 0) {
if (components.length === 0 || oneChangePerToken) {
// Nothing to merge into (or merging is disabled): the prefix becomes plain equal
// components - one per token under oneChangePerToken, one merged run otherwise.
if (oneChangePerToken) {
for (let i = 0; i < prefixLen; i++) {
prefixComponents.push({added: false, removed: false, count: 1});
}
} else {
prefixComponents.push({added: false, removed: false, count: prefixLen});
}
} else {
const first = components[0];
if (!first.added && !first.removed) {
first.count += prefixLen;
} else {
prefixComponents.push({added: false, removed: false, count: prefixLen});
}
}
}
// Rebuild the back-to-front linked list buildValues expects: the head is the LAST component
// in output order, and previousComponent links towards earlier components. The prefix
// components precede the loop's output.
let head: DraftChangeObject | undefined;
for (const component of prefixComponents) {
component.previousComponent = head;
head = component;
}
for (const component of components) {
component.previousComponent = head;
head = component;
}
let value = this.buildValues(head, newTokens, oldTokens);

@ExplodingCabbage ExplodingCabbage Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This seems crazy - am I misunderstanding? We (unconditionally!) do the (O(n)) reverse-linked-list-to-array conversion that was previously a significant chunk of this.buildValues's job, then we reinstate discarded tokens into that array... and then we REVERSE the conversion (again at cost O(n)), changing the type back to a reverse-linked-list, just so that we can pass buildValues the type it expects, at which point it repeats the (O(n)) work again? Surely it'd be simpler (and more performant) to just modify buildValues to expect an array? (Or possibly move all this logic into buildValues, I dunno which is better.) It's private; there's no user-facing API we need to preserve here.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

No misunderstanding - it really was that silly. buildValues now takes the array directly (it's private with one caller), the rebuild is gone, and dropping the previousComponent links moved into done's first walk since that already visits every component. It's also measurably faster, as you suspected - same seeded inputs, median of 5: 50%-shared diffLines 3.0ms -> ~2.2ms, ~50%-shared diffChars 4.0ms -> ~1.2ms.

Comment thread src/diff/base.ts Outdated
Comment on lines +226 to +228
// Total edit distance = loop-section edit distance + the fixed cost of the dropped tokens, so
// the loop must hit its maxEditLength abort one discardedTotal earlier than the caller's
// maxEditLength, preserving the documented abort semantics.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Interesting design dilemma here. Could make a case for NOT counting discarded tokens towards maxEditLength, since they don't have the same performance impact as insertions/deletions of non-discarded tokens. But probably your choice is the right one; I guess people may be relying on maxEditLength for more than just a worst-case-performance guarantee.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I'd like to keep the current behaviour: maxEditLength is a documented, user-visible contract (abort when the edit distance exceeds N), and counting the discarded tokens is what keeps it meaning exactly the same thing as before. Someone could in principle be using it as a cheap "are these more than N edits apart?" check, and that answer shouldn't change just because of an internal optimisation. (The performance protection is unaffected either way - the discarded tokens are O(n) to find and reinstate.)

Comment thread src/diff/base.ts Outdated
const newLen = newNormalized.length, oldLen = oldNormalized.length;

// Total edit distance = loop-section edit distance + the fixed cost of the dropped tokens, so
// the loop must hit its maxEditLength abort one discardedTotal earlier than the caller's

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Slightly garbled? "one discardedTotal" should say "discardedTotal iterations", right?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Yes - a leftover variable name from an earlier draft. The sentence is gone entirely now, since the maxEditLength -= rework below made it unnecessary.

Comment thread src/diff/base.ts Outdated
): ChangeObject<ValueT>[] | undefined {
const done = (value: ChangeObject<ValueT>[]) => {
const done = (lastComponent: DraftChangeObject | undefined) => {
// The loop produces components for the (possibly skeleton-of-the-) middle section only.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

We keep talking about the "middle section" in comments but that terminology no longer makes sense now that the PR only trims the prefix and not the suffix. We need another term. How about the "rump"?

(The reference later to the "loop section" should use the same terminology.)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Or, actually, you could just call it the skeleton, as you already do in places? (Or use rump consistently.) Many acceptable options!

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Good catch, and I went with rump. I kept "skeleton" as a distinct term because the code needs both: the rump is each input minus its cut prefix, and the skeleton is the rump minus its dropped tokens. expandDiscarded's whole job is turning skeleton components back into rump components, so collapsing the two names would have made that doc harder to write. Both are defined where they're first used, in the comment at the top of done.

Comment thread src/diff/base.ts Outdated
// The texts are identical (per the definition of "identical" implied by
// tokenize, normalizeToken, and equals).
return done(this.buildValues(initialPath.lastComponent, newTokens, oldTokens));
// The loop section is identical (per the definition of "identical" implied by

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Slightly odd to say the loop section (singular) is identical. Identical to what? If we're not going to refer in plural to the old and new versions like we were in the old version of the comment, perhaps a better adjective is "unchanged"?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

"unchanged" reads much better, adopted. The comment now says the main loop's inputs are unchanged and the full inputs differ only by the dropped tokens - which also covers the no-plan case, where the inputs are the full arrays.

Comment thread src/diff/base.ts Outdated
Comment on lines +229 to +230
const editLengthCap = maxEditLength
- (plan?.discard ? plan.discard.discardedOld + plan.discard.discardedNew : 0);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Does it really make sense to create a new constant here? Seems the names editLengthCap and maxEditLength are essentially synonyms, and it makes the rest of the function harder to follow knowing that both are in scope with different values. Why not just:

maxEditLength -= (plan?.discard ? plan.discard.discardedOld + plan.discard.discardedNew : 0);

instead? (Would require a tweak to the code for the case where the rump is unchanged, but I think that deserves a tweak anyway - will comment there.)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done, and it cascaded nicely: maxEditLength -= discarded in place, editLengthCap deleted, and the main loop's two abort conditions are now literally identical to master's.

Comment thread src/diff/base.ts Outdated
Comment on lines +236 to +243
// The loop section is identical (per the definition of "identical" implied by
// tokenize, normalizeToken, and equals). The full inputs may still differ by the dropped
// tokens, whose total edit cost is fixed; if that cost alone already exceeds maxEditLength,
// abort exactly as the unoptimised loop would have.
if (
plan?.discard
&& plan.discard.discardedOld + plan.discard.discardedNew > maxEditLength
) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Can't we more simply check for this case with just if (editLengthCap < 0)? (Or if (maxEditLength < 0), if you've already done https://github.com/kpdecker/jsdiff/pull/744/changes#r4755195829.)

For that matter, can't we check for this case immediately after we calculate editLengthCap, above? It's simpler to get this scenario (where discarding unique tokens has already taken us over the edit limit) out of the way immediately, before the logic branches into the identical-rump and non-identical-rump scenarios, so that we don't need to look to see how it's handled in each branch separately.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done - the abort moved out of the unchanged-skeleton branch and now sits directly under the subtraction (inside the if (plan) block, since without a plan maxEditLength is untouched and the check would be meaningless). The nested check in the branch is gone. Verified equivalence with an exhaustive sweep - every limit from 0 to 30 over 91 inputs, sync and async - which aborts on exactly the same values as master, including the boundary cases where the limit equals the discarded count or sits one either side.

…ignatures

Per review:

- `done` already walked the linked list into an array to reinstate the
  dropped tokens and the cut prefix, then rebuilt a linked list just so
  `buildValues` could walk it back into an array. `buildValues` is
  private with a single caller, so it now takes the array directly and
  the round trip is gone (dropping the `previousComponent` links moves
  into `done`'s first walk, which already visits every component).
  Measured on the same seeded inputs, median of 5: diffLines 6000 lines
  50% shared 3.00ms -> 2.22ms, diffChars 8000x8000 ~50% shared
  3.99ms -> 1.12ms, 10% shared 2.51ms -> 1.76ms.
- The discarded tokens' cost is now subtracted from `maxEditLength`
  itself, and the "the discarded tokens alone exceed the limit" abort
  happens immediately after, before the logic branches on whether the
  skeleton is unchanged. The separate `editLengthCap` constant is gone
  and the main loop's abort conditions read exactly as they do on master.
- `DiscardPlan.discard` is now required. It was optional only while a
  trim-only plan shape existed; since the Set rework every plan carries
  it, so the "always present" comment on an optional field is gone and
  the `plan?.discard` checks collapse to `plan`.
- `expandDiscarded` takes the plan instead of five loosely related
  arguments (`prefixLen`, `endOld`, `endNew` and the discard record),
  and derives the rump ends from it; the two helpers inside
  `buildDiscardPlan` lose `start`/`end` parameters that were only ever
  called with `prefixLen` and the array length.
- Comments: what remains after the common prefix is cut is now called
  the rump (the skeleton is the rump minus its dropped tokens), since
  "middle section" stopped making sense once the suffix was left in
  place; "the main loop" (defined once, in `done`) replaces the
  ambiguous "the loop" wherever this PR introduced it; the garbled "one
  discardedTotal earlier" sentence is rewritten; the index maps are
  described as pointing into the normalized input rather than the
  original token array; comments that argued for a threshold that no
  longer exists, or taught subclass authors how to write subclasses, are
  removed; and an unrelated whitespace change to an untouched line is
  reverted.

346/346 tests, eslint clean, 9000 fuzz cases across all diff functions
x option combinations remain byte-identical to master, an exhaustive
maxEditLength sweep (every limit from 0 to 30 over 91 inputs, sync and
async) aborts on exactly the same values as master, and the 200k-token
`oneChangePerToken` cases still run without a spread call anywhere.
@yuluod

yuluod commented Dec 1, 2026

Copy link
Copy Markdown
Author

Pushed d00bbd4, which addresses all of the second-round comments (4754575305 through 4755308130) plus a pass of my own over the same kinds of issues. In short:

  • buildValues takes the component array directly; the linked-list ↔ array round trip is gone (and it's measurably faster - see the reply on 4754817686).
  • maxEditLength -= discarded in place, abort moved above the unchanged-skeleton branch, editLengthCap deleted; the main loop's abort conditions are now literally identical to master's.
  • discard is required; expandDiscarded takes the plan instead of five loosely related arguments; the helpers in buildDiscardPlan lose start/end parameters that were only ever called with one value.
  • Terminology: rump (what's left after the prefix cut) and skeleton (rump minus dropped tokens), "the main loop" defined once at done.
  • Removed comments that were arguing for a threshold that no longer exists, teaching subclass authors how to write subclasses, or describing the index maps as pointing into the original token array (they point into the normalized input).

Verification on the pushed commit: 346/346, eslint clean, 9000 fuzz cases byte-identical to the base commit, an exhaustive maxEditLength sweep (every limit 0..30 over 91 inputs, sync and async) aborting on exactly the same values as master, and the 200k-token oneChangePerToken cases still fine. PR description updated to match (the "verified empirically" hedge, the discardedTotal sentence, and the pre-rework benchmark numbers are gone).

@ExplodingCabbage
ExplodingCabbage requested a max review from Copilot December 2, 2026 11:06

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.

🟡 Changes recommended

Fast-path regressions bypass expired timeouts for differing inputs and reject identical inputs with negative maxEditLength, while the timer-clamping test no longer exercises Myers iterations.

3 open issues
What changed in this PR

Building on token normalization in #732, this PR reduces Myers-loop work for low-overlap inputs, addressing the performance portion of #720.

Changes:

  • Cut common prefixes and discard tokens unique to one side, then reconstruct full change components.
  • Reduce edit budgets by discarded-token counts and guard unsupported equality cases.
  • Update async timer-fairness inputs to retain iterative work.
File Description
test/​diff/​character.js Keeps the timer-fairness test from taking the optimized shortcut.
src/​diff/​base.ts Adds discard planning, component reconstruction, and edit-budget adjustment.

Review effort: Max

Comment thread src/diff/base.ts Resolved
Comment thread src/diff/base.ts Resolved
Comment thread test/diff/character.js Outdated
// other stuff to run - that is after all the point of async mode!
const oldText = 'ax'.repeat(1000);
const newText = 'ay'.repeat(1000);
// (Inputs chosen to not trigger the discard-unique-tokens optimisation: 'a' and 'b' both

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Huh, confusing - the comment you've made (about the "should not wait for a timer between iterations in async mode" test) makes perfect sense, but you've made it on a totally different test case.

This branch has not been deployed

No deployments
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.

5 participants