Repository navigation
Description
Issue description
OrmUtils.deepCompare is called by SubjectChangedColumnsComputer on every save() for each json / jsonb column and each array column to decide whether the column changed. For unchanged values, which is the common case when saving a loaded entity, it traverses the whole value. With larger JSON documents this becomes a noticeable part of the save cost.
Expected Behavior
Comparing two equal JSON values costs roughly one traversal of the value.
Actual Behavior
compare2Objects (the body of deepCompare) is 9-14 times slower than a straightforward deep-equal on equal values (median of 15-50 runs, Node 24.22, TypeORM 1.1.1; compare2Objects is unchanged in 1.1.2 and on master):
| objects in the JSON array | OrmUtils.compare2Objects |
fast-deep-equal/es6 |
factor |
|---|---|---|---|
| 100 | 0.72 ms | 0.08 ms | 9.0x |
| 1,000 | 6.65 ms | 0.49 ms | 13.7x |
| 7,000 | 48.34 ms | 4.35 ms | 11.1x |
| 20,000 | 143.58 ms | 12.37 ms | 11.6x |
Each object is { id, name, enabled, tags: ["a", "b", "c"], meta: { createdBy, score, nested: { level, values: [1, 2, 3] } } }.
From reading the implementation, the cost comes from:
- two passes over the keys of every object (the "subset" loop over
y, then the loop overx), each with twohasOwnPropertyand twotypeofchecks per key - the cycle check
leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1, a linear scan per visited object, pluspush/popon both chains for every nested property - the
isPrototypeOf,constructor,prototypeandequalschecks that run for every nested object before its keys are compared
Steps to reproduce
Benchmark script (no database needed; it calls the exported OrmUtils.compare2Objects directly):
// node bench-deep-compare.cjs <path-to-typeorm-package> <path-to-fast-deep-equal-package>
// Benchmark: TypeORM's stock OrmUtils.compare2Objects (the body of deepCompare) against fast-deep-equal/es6
// on json column values of growing size. Equal values are the common case on save() of an unchanged entity
// and force a full traversal.
// Usage: node bench-deep-compare.cjs <path-to-typeorm-package> <path-to-fast-deep-equal-package>
const path = require("node:path");
const { OrmUtils } = require(path.join(process.argv[2], "util/OrmUtils.js"));
const fastDeepEqual = require(path.join(process.argv[3], "es6/index.js"));
const stockDeepCompare = (a, b) => OrmUtils.compare2Objects([], [], a, b);
function buildValue(count) {
return Array.from({ length: count }, (_, i) => ({
id: i,
name: `item-${i}`,
enabled: i % 2 === 0,
tags: ["a", "b", "c"],
meta: { createdBy: "user", score: i * 1.5, nested: { level: 2, values: [1, 2, 3] } },
}));
}
function measure(fn, a, b, rounds) {
for (let i = 0; i < 3; i++) fn(a, b);
const times = [];
for (let i = 0; i < rounds; i++) {
const start = process.hrtime.bigint();
const result = fn(a, b);
times.push(Number(process.hrtime.bigint() - start) / 1e6);
if (result !== true) throw new Error("expected equal values");
}
times.sort((x, y) => x - y);
return times[Math.floor(times.length / 2)];
}
console.log(`node ${process.version}`);
console.log("objects | stock compare2Objects (ms, median) | fast-deep-equal/es6 (ms, median) | factor");
for (const count of [100, 1000, 7000, 20000]) {
const a = buildValue(count);
const b = structuredClone(a);
const rounds = count >= 7000 ? 15 : 50;
const stock = measure(stockDeepCompare, a, b, rounds);
const fast = measure(fastDeepEqual, a, b, rounds);
console.log(`${count} | ${stock.toFixed(2)} | ${fast.toFixed(2)} | ${(stock / fast).toFixed(1)}x`);
}My Environment
| Dependency | Version |
|---|---|
| Operating System | Linux |
| Node.js version | 24.22.0 |
| Typescript version | 5.9.3 |
| TypeORM version | 1.1.1 |
Additional Context
- We have patched
deepCompareto delegate tofast-deep-equalsince TypeORM 0.2.x because of this. We would like to drop that patch. - A new dependency is probably not the right fix:
fast-deep-equaldoes not cover whatcompare2Objectshandles today (.equals(), see Repository.save() doesn't not check id correctly when id is buffer type. #3654;Uint8Array;Map/Set, see OrmUtils.deepCompare cannot compare Map objects #10989 / fix: fix up map objects comparison #10990). An optimised in-house comparison that keeps those semantics (single pass with a key-count check, early type dispatch, aWeakSetor depth-only cycle guard instead ofindexOfon arrays) should get close to the numbers above. - Open PR fix: compare entity ids of mixed string/number type as equal #12780 changes
OrmUtils.compareIdsonly and leavescompare2Objectsuntouched, so it does not overlap with this.
Relevant Database Driver(s)
- mysql
- postgres
- (all drivers that use
json/jsonbor array columns)
Are you willing to resolve this issue by submitting a Pull Request?
Maybe, after feedback on the preferred approach.
Activity
perf(persistence): speed up deepCompare for json and array columns
perf(persistence): speed up deepCompare for json and array columns