Skip to content

perf(persistence): speed up deepCompare for json and array columns - #13000

Open
ElwinErnst wants to merge 1 commit into
typeorm:masterfrom
ElwinErnst:fix/deep-compare-perf
Open

ElwinErnst wants to merge 1 commit into
typeorm:masterfrom
ElwinErnst:fix/deep-compare-perf

Conversation

@ElwinErnst

Copy link
Copy Markdown

Description of change

OrmUtils.deepCompare (compare2Objects) runs on every save() for each json/jsonb column and each array column, via SubjectChangedColumnsComputer, to decide whether the column changed. On unchanged values — the common case when saving a loaded entity — it traverses the whole value, and it did so ~8–14x slower than a straightforward deep-equal (see #12995 for the benchmark and analysis).

What changed

compare2Objects is rewritten to:

  • do a single pass over each object's keys (previously two full passes, each with two hasOwnProperty and two typeof checks per key), with a lighter second pass that only rejects keys present on the right object but not the left;
  • take a positional fast path for arrays (the common shape inside json columns), applying the same per-element rules as the object walk;
  • hoist repeated iterableX[p] / typeof lookups into locals.

Semantics are preserved exactly — .equals() (Buffer, #3654), Uint8Array, Map/Set, Date/RegExp, the NaN handling for primitive members, and cycle detection all behave as before.

How it was verified

  • The issue's benchmark (Node, array of N objects): 20,000 objects 63.8 ms → 7.7 ms (~8.3x); consistent ~6–8x at smaller sizes.
  • A 200,000-case differential fuzz comparing the new implementation against the previous one over randomly generated nested values (objects, arrays, Map/Set, Date/RegExp, NaN, null/undefined, near-equal clones): 0 divergences.
  • Unit tests expanded from 3 to 12 cases in test/unit/util/orm-utils.test.ts (arrays, nested, extra keys, Date/RegExp, cycles, null/undefined).

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links relevant issues as Fixes #00000
  • There are new or updated tests validating the change (tests/**.test.ts)
  • Documentation has been updated to reflect this change (docs/docs/**.md) — N/A (internal behavior, no public API change)

Fixes #12995

@github-actions github-actions Bot added linked-issue PR references an issue possible-duplicate PR may duplicate an existing open PR labels Oct 24, 2026
@github-actions

Copy link
Copy Markdown

Other open PRs also reference #12995: #12999. Maintainers may want to coordinate.

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Array-like objects pass as real arrays ✓ Resolved
Description
The array fast path assumes that matching constructors make y an array, then checks only its
length and indexed values. When y is a non-array object such as `{ constructor: Array, length: 0
}, deepCompare([], y)` now returns true, allowing a JSON or array-column change to be treated as
unchanged.
Code

packages/typeorm/src/util/OrmUtils.ts[R504-506]

+        // x and y share a constructor here, so y is an array too.
+        if (Array.isArray(x)) {
+            if (x.length !== y.length) return false
Evidence
The existing constructor and prototype checks accept this object, but only x is checked with
Array.isArray; equal lengths then lead straight to the successful return. The tests already
establish that arrays and objects should compare differently, and persistence uses this comparison
to decide whether JSON and array columns changed.

packages/typeorm/src/util/OrmUtils.ts[483-505]
packages/typeorm/src/util/OrmUtils.ts[505-542]
packages/typeorm/test/unit/util/orm-utils.test.ts[323-325]
packages/typeorm/src/persistence/SubjectChangedColumnsComputer.ts[179-186]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The array fast path accepts a non-array right-hand value when it has the Array constructor and matching length and indexes.
## Fix Focus Areas
- packages/typeorm/src/util/OrmUtils.ts[500-506]
- packages/typeorm/test/unit/util/orm-utils.test.ts[323-325]
## Recommended Fix
Check `Array.isArray(y)` before entering the positional path and return false for an array/non-array pair. Add a regression test using a non-array object with `constructor: Array` and matching length.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Accessor changes can go undetected 🐞 Bug ≡ Correctness
Description
The new object pass reads iterableX[p] before iterableY[p] and never revisits their values,
reversing the former Y-first read order. If Y's accessor changes the value returned by X's accessor,
deepCompare can accept the earlier X value as equal even though reading X after that change would
reveal a difference; accessor- or proxy-backed values passed to JSON change detection are affected.
Code

packages/typeorm/src/util/OrmUtils.ts[R569-570]

+            const valueX = iterableX[p]
+            const valueY = iterableY[p]
Evidence
For let value = 1, X with get a() { return value }, and Y with `get a() { value = 2; return 1
}, the new X-then-Y read compares 1 with 1` and returns true. The deleted first pass read Y
before X, so the subsequent value comparison observed X as 2 and Y as 1; the new second pass
checks only key presence.

packages/typeorm/src/util/OrmUtils.ts[562-575]
packages/typeorm/src/util/OrmUtils.ts[592-607]
packages/typeorm/src/persistence/SubjectChangedColumnsComputer.ts[179-186]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Changing the order and number of property reads makes comparisons of accessor-backed objects depend on stale values.
## Fix Focus Areas
- packages/typeorm/src/util/OrmUtils.ts[562-607]
- packages/typeorm/test/unit/util/orm-utils.test.ts[287-303]
## Recommended Fix
Add a regression test where Y's getter changes the value returned by X's getter. Preserve the former read behavior for accessor-backed properties while retaining the single-pass optimization for ordinary data properties.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Array property changes go undetected ⊘ Outdated
Description
compare2Objects returns from the new array branch after comparing only length and indexed
values, without checking enumerable named properties. Two arrays such as [1] with different
extra values now compare equal, whereas the former property walk detected the difference,
including when the arrays are nested in compared objects.
Code

src/util/OrmUtils.ts[R533-536]

+            }
+            leftChain.pop()
+            rightChain.pop()
+            return true
Evidence
The array branch returns without enumerating properties, while deepCompare can reach this branch
recursively and through persistence change detection.

src/util/OrmUtils.ts[499-537]
src/persistence/SubjectChangedColumnsComputer.ts[166-176]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The array fast path treats arrays with different enumerable named properties as equal.
## Fix Focus Areas
- src/util/OrmUtils.ts[499-537]
## Recommended Fix
Retain positional comparison for ordinary indices, then compare enumerable non-index properties and their ownership using the generic object comparison rules. Add a regression test with differing named properties.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View review recommended (2)
4. Sparse array entries compare as present ⊘ Outdated
Description
compare2Objects reads x[i] and y[i] without checking whether either array owns that index, so
a hole and an explicit undefined both read as undefined. For example, new Array(1) and
[undefined] now compare equal; the former enumerable-key walk rejected their different index
ownership, and compareIds also delegates non-primitive identifiers to this comparison.
Code

src/util/OrmUtils.ts[R504-506]

+            for (let i = 0; i < x.length; i++) {
+                const valueX = x[i]
+                const valueY = y[i]
Evidence
The new loop compares positional reads rather than key ownership. compareIds uses deepCompare
for identifiers outside its primitive-ID shortcut.

src/util/OrmUtils.ts[499-528]
src/util/OrmUtils.ts[220-246]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The positional array comparison cannot distinguish an absent index from an index containing undefined.
## Fix Focus Areas
- src/util/OrmUtils.ts[504-528]
## Recommended Fix
For each index, compare own-property presence before reading and comparing values. Add a regression test for a sparse array versus an array containing explicit undefined.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Large sparse arrays stall comparison ⊘ Outdated
Description
compare2Objects now loops over every position up to x.length, even when neither array contains
an element at most of those positions. Comparing two distinct arrays created with a very large
length therefore takes time proportional to that length instead of iterating only their enumerable
keys as the former walk did, including on the array-column save path.
Code

src/util/OrmUtils.ts[R500-505]

+            if (x.length !== y.length) return false
+
+            leftChain.push(x)
+            rightChain.push(y)
+            for (let i = 0; i < x.length; i++) {
+                const valueX = x[i]
Evidence
The new loop is bounded by array length, not the number of present keys; array-column change
detection calls deepCompare.

src/util/OrmUtils.ts[499-505]
src/persistence/SubjectChangedColumnsComputer.ts[201-206]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The positional fast path scans every slot of a large sparse array, including absent slots.
## Fix Focus Areas
- src/util/OrmUtils.ts[499-537]
## Recommended Fix
Keep the positional path for dense arrays, but compare enumerable keys for sparse arrays so work scales with their present entries. Add a regression test using large, mostly empty arrays.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

Grey Divider

Context sources
Review mode: Auto: ⚖️ Balanced: Core comparator rewrite carries real semantic risk, but remains localized.

Grey Divider

Tip of the day
💡 Did you know, you can enable the Remediation agent and Qodo fixes findings in a dedicated fix PR

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous reviews

Review updated until commit 2153c11 ⚖️ Balanced

Results up to commit 2ab1dc8


🐞 Bugs (2) 📘 Rule violations (0) 📎 Requirement gaps (0) 📜 Skill insights (0)


Remediation recommended
1. Array-like objects pass as real arrays 🐞 Bug ≡ Correctness ⭐ New
Description
The array fast path assumes that matching constructors make y an array, then checks only its
length and indexed values. When y is a non-array object such as `{ constructor: Array, length: 0
}, deepCompare([], y)` now returns true, allowing a JSON or array-column change to be treated as
unchanged.
Code

packages/typeorm/src/util/OrmUtils.ts[R504-506]

+        // x and y share a constructor here, so y is an array too.
+        if (Array.isArray(x)) {
+            if (x.length !== y.length) return false
Evidence
The existing constructor and prototype checks accept this object, but only x is checked with
Array.isArray; equal lengths then lead straight to the successful return. The tests already
establish that arrays and objects should compare differently, and persistence uses this comparison
to decide whether JSON and array columns changed.

packages/typeorm/src/util/OrmUtils.ts[483-505]
packages/typeorm/src/util/OrmUtils.ts[505-542]
packages/typeorm/test/unit/util/orm-utils.test.ts[323-325]
packages/typeorm/src/persistence/SubjectChangedColumnsComputer.ts[179-186]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The array fast path accepts a non-array right-hand value when it has the Array constructor and matching length and indexes.

## Fix Focus Areas
- packages/typeorm/src/util/OrmUtils.ts[500-506]
- packages/typeorm/test/unit/util/orm-utils.test.ts[323-325]

## Recommended Fix
Check `Array.isArray(y)` before entering the positional path and return false for an array/non-array pair. Add a regression test using a non-array object with `constructor: Array` and matching length.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Accessor changes can go undetected 🐞 Bug ≡ Correctness ⭐ New
Description
The new object pass reads iterableX[p] before iterableY[p] and never revisits their values,
reversing the former Y-first read order. If Y's accessor changes the value returned by X's accessor,
deepCompare can accept the earlier X value as equal even though reading X after that change would
reveal a difference; accessor- or proxy-backed values passed to JSON change detection are affected.
Code

packages/typeorm/src/util/OrmUtils.ts[R569-570]

+            const valueX = iterableX[p]
+            const valueY = iterableY[p]
Evidence
For let value = 1, X with get a() { return value }, and Y with `get a() { value = 2; return 1
}, the new X-then-Y read compares 1 with 1` and returns true. The deleted first pass read Y
before X, so the subsequent value comparison observed X as 2 and Y as 1; the new second pass
checks only key presence.

packages/typeorm/src/util/OrmUtils.ts[562-575]
packages/typeorm/src/util/OrmUtils.ts[592-607]
packages/typeorm/src/persistence/SubjectChangedColumnsComputer.ts[179-186]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Changing the order and number of property reads makes comparisons of accessor-backed objects depend on stale values.

## Fix Focus Areas
- packages/typeorm/src/util/OrmUtils.ts[562-607]
- packages/typeorm/test/unit/util/orm-utils.test.ts[287-303]

## Recommended Fix
Add a regression test where Y's getter changes the value returned by X's getter. Preserve the former read behavior for accessor-backed properties while retaining the single-pass optimization for ordinary data properties.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Array property changes go undetected ⊘ Outdated
Description
compare2Objects returns from the new array branch after comparing only length and indexed
values, without checking enumerable named properties. Two arrays such as [1] with different
extra values now compare equal, whereas the former property walk detected the difference,
including when the arrays are nested in compared objects.
Code

src/util/OrmUtils.ts[R533-536]

+            }
+            leftChain.pop()
+            rightChain.pop()
+            return true
Evidence
The array branch returns without enumerating properties, while deepCompare can reach this branch
recursively and through persistence change detection.

src/util/OrmUtils.ts[499-537]
src/persistence/SubjectChangedColumnsComputer.ts[166-176]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The array fast path treats arrays with different enumerable named properties as equal.
## Fix Focus Areas
- src/util/OrmUtils.ts[499-537]
## Recommended Fix
Retain positional comparison for ordinary indices, then compare enumerable non-index properties and their ownership using the generic object comparison rules. Add a regression test with differing named properties.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View review recommended (2)
4. Sparse array entries compare as present ⊘ Outdated
Description
compare2Objects reads x[i] and y[i] without checking whether either array owns that index, so
a hole and an explicit undefined both read as undefined. For example, new Array(1) and
[undefined] now compare equal; the former enumerable-key walk rejected their different index
ownership, and compareIds also delegates non-primitive identifiers to this comparison.
Code

src/util/OrmUtils.ts[R504-506]

+            for (let i = 0; i < x.length; i++) {
+                const valueX = x[i]
+                const valueY = y[i]
Evidence
The new loop compares positional reads rather than key ownership. compareIds uses deepCompare
for identifiers outside its primitive-ID shortcut.

src/util/OrmUtils.ts[499-528]
src/util/OrmUtils.ts[220-246]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The positional array comparison cannot distinguish an absent index from an index containing undefined.
## Fix Focus Areas
- src/util/OrmUtils.ts[504-528]
## Recommended Fix
For each index, compare own-property presence before reading and comparing values. Add a regression test for a sparse array versus an array containing explicit undefined.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Large sparse arrays stall comparison ⊘ Outdated
Description
compare2Objects now loops over every position up to x.length, even when neither array contains
an element at most of those positions. Comparing two distinct arrays created with a very large
length therefore takes time proportional to that length instead of iterating only their enumerable
keys as the former walk did, including on the array-column save path.
Code

src/util/OrmUtils.ts[R500-505]

+            if (x.length !== y.length) return false
+
+            leftChain.push(x)
+            rightChain.push(y)
+            for (let i = 0; i < x.length; i++) {
+                const valueX = x[i]
Evidence
The new loop is bounded by array length, not the number of present keys; array-column change
detection calls deepCompare.

src/util/OrmUtils.ts[499-505]
src/persistence/SubjectChangedColumnsComputer.ts[201-206]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The positional fast path scans every slot of a large sparse array, including absent slots.
## Fix Focus Areas
- src/util/OrmUtils.ts[499-537]
## Recommended Fix
Keep the positional path for dense arrays, but compare enumerable keys for sparse arrays so work scales with their present entries. Add a regression test using large, mostly empty arrays.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Context sources
Review mode: Auto: ⚖️ Balanced: Core persistence comparison logic changed, with substantial semantic and cycle-handling risk.
Results up to commit da9a5f4


🐞 Bugs (3) 📘 Rule violations (0) 📎 Requirement gaps (0) 📜 Skill insights (0)


Remediation recommended
1. Array property changes go undetected 🐞 Bug ≡ Correctness
Description
compare2Objects returns from the new array branch after comparing only length and indexed
values, without checking enumerable named properties. Two arrays such as [1] with different
extra values now compare equal, whereas the former property walk detected the difference,
including when the arrays are nested in compared objects.
Code

src/util/OrmUtils.ts[R533-536]

+            }
+            leftChain.pop()
+            rightChain.pop()
+            return true
Evidence
The array branch returns without enumerating properties, while deepCompare can reach this branch
recursively and through persistence change detection.

src/util/OrmUtils.ts[499-537]
src/persistence/SubjectChangedColumnsComputer.ts[166-176]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The array fast path treats arrays with different enumerable named properties as equal.
## Fix Focus Areas
- src/util/OrmUtils.ts[499-537]
## Recommended Fix
Retain positional comparison for ordinary indices, then compare enumerable non-index properties and their ownership using the generic object comparison rules. Add a regression test with differing named properties.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Sparse array entries compare as present 🐞 Bug ≡ Correctness
Description
compare2Objects reads x[i] and y[i] without checking whether either array owns that index, so
a hole and an explicit undefined both read as undefined. For example, new Array(1) and
[undefined] now compare equal; the former enumerable-key walk rejected their different index
ownership, and compareIds also delegates non-primitive identifiers to this comparison.
Code

src/util/OrmUtils.ts[R504-506]

+            for (let i = 0; i < x.length; i++) {
+                const valueX = x[i]
+                const valueY = y[i]
Evidence
The new loop compares positional reads rather than key ownership. compareIds uses deepCompare
for identifiers outside its primitive-ID shortcut.

src/util/OrmUtils.ts[499-528]
src/util/OrmUtils.ts[220-246]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The positional array comparison cannot distinguish an absent index from an index containing undefined.
## Fix Focus Areas
- src/util/OrmUtils.ts[504-528]
## Recommended Fix
For each index, compare own-property presence before reading and comparing values. Add a regression test for a sparse array versus an array containing explicit undefined.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Large sparse arrays stall comparison 🐞 Bug ➹ Performance
Description
compare2Objects now loops over every position up to x.length, even when neither array contains
an element at most of those positions. Comparing two distinct arrays created with a very large
length therefore takes time proportional to that length instead of iterating only their enumerable
keys as the former walk did, including on the array-column save path.
Code

src/util/OrmUtils.ts[R500-505]

+            if (x.length !== y.length) return false
+
+            leftChain.push(x)
+            rightChain.push(y)
+            for (let i = 0; i < x.length; i++) {
+                const valueX = x[i]
Evidence
The new loop is bounded by array length, not the number of present keys; array-column change
detection calls deepCompare.

src/util/OrmUtils.ts[499-505]
src/persistence/SubjectChangedColumnsComputer.ts[201-206]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The positional fast path scans every slot of a large sparse array, including absent slots.
## Fix Focus Areas
- src/util/OrmUtils.ts[499-537]
## Recommended Fix
Keep the positional path for dense arrays, but compare enumerable keys for sparse arrays so work scales with their present entries. Add a regression test using large, mostly empty arrays.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Context sources
Review mode: Auto: ⚖️ Balanced: Core deep-comparison semantics changed across arrays, cycles, and special objects.

Grey Divider

Qodo Logo

@ElwinErnst
ElwinErnst force-pushed the fix/deep-compare-perf branch from da9a5f4 to 2ab1dc8 Compare October 24, 2026 13:52
OrmUtils.deepCompare runs on every save() for each json/jsonb and array
column to detect changes. On unchanged values (the common case when
saving a loaded entity) it did two full passes over every object's keys
and ran per-key hasOwnProperty/typeof checks twice, making it ~8-14x
slower than a straightforward deep-equal.

Rewrite compare2Objects to a single pass over the keys with a lighter
second pass that only rejects keys unique to the right object, plus a
positional fast path for arrays. Element-level semantics (.equals,
Uint8Array, Map/Set, Date/RegExp, NaN, cycle detection) are preserved
exactly, verified by a 200k-case differential fuzz against the previous
implementation.

Measured on the issue's benchmark (Node 24, array of N objects):
20000 objects 63.8ms -> 7.7ms (~8.3x).

Closes typeorm#12995
@ElwinErnst
ElwinErnst force-pushed the fix/deep-compare-perf branch from 2ab1dc8 to 2153c11 Compare October 25, 2026 16:27
@ElwinErnst

Copy link
Copy Markdown
Author

Thanks for the automated review — I went through the array fast-path findings:

Array-like object slipping through ({ constructor: Array, length: 0 } comparing equal to []): valid catch, and the one that could actually mask a change, so it's fixed. The fast path now guards Array.isArray(y) explicitly instead of inferring it from the constructor match, with a regression test (should not treat an array-like object as an equal array).

Holes, non-index enumerable properties, sparse-array iteration, and getter read order: these are left as deliberate fast-deep-equal-equivalent semantics, which is what #12995 asks for (the reporter has been patching deepCompare to delegate to fast-deep-equal and wants to drop that patch). They're unreachable for the values this function actually compares on save() — json/jsonb and array column values produced by JSON.parse and the array parsers are always dense, without non-index properties or accessor-backed members. I measured the alternative: adding per-index in checks plus a non-index-property pass drops the speedup from ~8.9x to ~4.1x on the issue's benchmark, for cases that can't occur with real column data. I added a code comment documenting the choice.

200k-case differential fuzz against the previous implementation still reports 0 divergences, and the unit suite passes.

@pkg-pr-new

pkg-pr-new Bot commented Oct 25, 2026

Copy link
Copy Markdown
  • typeorm-sql-js-example

    npm i https://pkg.pr.new/typeorm@13000
    

commit: 2153c11

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

linked-issue PR references an issue possible-duplicate PR may duplicate an existing open PR

Development

Successfully merging this pull request may close these issues.

perf: OrmUtils.deepCompare is 9-14x slower than necessary for json columns and array columns on save

1 participant