Repository navigation
Conversation
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.
There was a problem hiding this comment.
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.
| const skNorm: TokenT[] = []; | ||
| const skToOrig: number[] = []; | ||
| for (let i = 0; i < tokens.length; i++) { | ||
| if ((otherCounts.get(normalized[i] as string) ?? 0) > 0) { |
There was a problem hiding this comment.
Arrays are typed TokenT[], but then values are cast to string throughout?
There was a problem hiding this comment.
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).
| oldSk: oldS.sk, | ||
| newSk: newS.sk, |
There was a problem hiding this comment.
Do we ever read values out of these arrays, I can only find .length? If so, would just a counter be more efficient?
There was a problem hiding this comment.
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).
|
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 Dead skeleton arrays - you were right, only Types - single eslint - fixed ( 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 |
| // 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 |
There was a problem hiding this comment.
Simpler: "A token that occurs (post-normalization) on only one side must be an insertion or deletion."
| // 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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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!)
There was a problem hiding this comment.
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.
| * - `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 |
There was a problem hiding this comment.
Should be "any normalized token", I guess? I figure tokens don't strictly speaking need to stay the same type when normalized.
There was a problem hiding this comment.
Fixed ("any normalized token is not a string").
|
|
||
| /** | ||
| * 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 |
There was a problem hiding this comment.
As with a bunch of other places, the comment here suggests we trim the common SUFFIX too, but in fact we don't.
There was a problem hiding this comment.
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.
| * 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. |
There was a problem hiding this comment.
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.)
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
| // 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.)
| // 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 |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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:
- Position bookkeeping. Skipping a unique token advances only one side, so
newPos = oldPos - kstops holding - andextractCommon, thecanAdd/canRemovebounds checks and thebestPathindexing all depend on it. EveryPathwould have to carry a physicalnewPosseparate from the logical diagonal. - 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
expandDiscardedreproduces 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 - effectivelyexpandDiscardedmoved into the loop. - 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. - 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.
| let discardedByOld = 0; | ||
| let discardedNew = 0; |
There was a problem hiding this comment.
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".
There was a problem hiding this comment.
Gone with the Set rewrite below - the counts are derived from the skeleton lengths, there are no summation locals at all anymore.
| const midOldEnd = oldNorm.length; | ||
| const midNewEnd = newNorm.length; |
There was a problem hiding this comment.
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.)
There was a problem hiding this comment.
Removed - they were indeed leftovers from when suffix trimming was still on the cards.
| }; | ||
| const midOldLen = midOldEnd - prefixLen; | ||
| const midNewLen = midNewEnd - prefixLen; | ||
| if (discardedByOld + discardedNew < (midOldLen + midNewLen) * 0.2) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| * - 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| /** Always present in a returned plan: every plan that passes the guards drops the tokens | ||
| * unique to one side. */ | ||
| discard?: { |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
| ): 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. |
There was a problem hiding this comment.
"The loop" here seems unhelpfully ambiguous. I guess we mean something like "The main Myers algorithm loop, implemented below via repeated calls to execEditLength,"?
There was a problem hiding this comment.
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.
| 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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| // 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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.)
| 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 |
There was a problem hiding this comment.
Slightly garbled? "one discardedTotal" should say "discardedTotal iterations", right?
There was a problem hiding this comment.
Yes - a leftover variable name from an earlier draft. The sentence is gone entirely now, since the maxEditLength -= rework below made it unnecessary.
| ): 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. |
There was a problem hiding this comment.
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.)
There was a problem hiding this comment.
Or, actually, you could just call it the skeleton, as you already do in places? (Or use rump consistently.) Many acceptable options!
There was a problem hiding this comment.
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.
| // 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 |
There was a problem hiding this comment.
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"?
There was a problem hiding this comment.
"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.
| const editLengthCap = maxEditLength | ||
| - (plan?.discard ? plan.discard.discardedOld + plan.discard.discardedNew : 0); |
There was a problem hiding this comment.
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.)
There was a problem hiding this comment.
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.
| // 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 | ||
| ) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Pushed
Verification on the pushed commit: 346/346, eslint clean, 9000 fuzz cases byte-identical to the base commit, an exhaustive |
There was a problem hiding this comment.
🟡 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
| // 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 |
There was a problem hiding this comment.
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.


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
buildValuesslices the original token arrays. Two facts make byte-identical output achievable:addToPathand 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.buildValuesreconstructs values from the counts alone. Equal components are split wherever dropped tokens are wedged between their matched tokens.maxEditLengthsemantics 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:
comparatoris passed (equality semantics unknown, so equal tokens may have different normalized values),equalsis overridden by a subclass (same problem),===thatequalsuses).Verification
'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.oneChangePerToken,maxEditLength,timeout,newlineIsToken,stripTrailingCr; string pools spanning zero/high overlap; empty/whitespace-only inputs. Zero output differences.maxEditLengthsweep: every limit from 0 to 30 over 91 inputs, sync and async, aborts on exactly the same values as the base commit.oneChangePerToken(the largest component arrays this PR produces) run without error and match the base commit.timeoutnow 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,
buildValuestaking the component array directly):diffChars8000×8000, zero overlapdiffChars8000×8000, ~50% shareddiffLines6000 lines, 1% shareddiffLines6000 lines, 10% shareddiffLines6000 lines, 50% shareddiffLines6000 lines, realistic small editThe 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
Mapcounting it required cost more than the skeleton work it saved.