Object Comparison
@blazediff/object takes two JavaScript values and returns a flat list of what
changed, with the path to each change. It handles nested objects, arrays, dates,
regexes and circular references, and it is about 55% faster than
microdiffΒ across the benchmark
fixtures.
This is the one part of BlazeDiff that has nothing to do with images. It shares
the name and the performance work, not the pipeline. Use it for audit logs,
undo stacks, state-change assertions in tests, or anywhere you would otherwise
JSON.stringify two objects and compare strings.
Installation
npm install @blazediff/objectWhat you get back
One entry per change, always the same shape, so V8 keeps a single hidden class for the whole array:
interface Difference {
type: 0 | 1 | 2; // CREATE | REMOVE | CHANGE
path: (string | number)[]; // e.g. ["user", "settings", "theme"]
value: unknown; // the new value
oldValue: unknown; // the previous value
}Types are numbers rather than strings on purpose: they get compared in the hot
loop. 0 is CREATE, 1 is REMOVE, 2 is CHANGE.
Examples
Basic Comparison
{
"a": 1,
"b": 2,
"c": 3
}Old Object
{
"a": 1,
"b": 20,
"d": 4
}New Object
Result
import diff from "@blazediff/object";
const oldObj = { a: 1, b: 2, c: 3 };
const newObj = { a: 1, b: 20, d: 4 };
// b changed, c was removed, d was created. a is not reported.
const changes = diff(oldObj, newObj);Things worth knowing
- Arrays are compared by index, not by identity. Inserting at the front reports every following element as a CHANGE. If you need move detection, key the array yourself before diffing.
- Cycles are handled, and the check costs something. If you know your input is
a tree, pass
{ detectCycles: false }. - Unchanged values are not reported. An empty array means the two inputs are structurally equal.
What it costs
Against microdiff, M1 Max, Node 22, 10,000 iterations:
| Fixture | microdiff | @blazediff/object |
|---|---|---|
| Large nested object | 3.3318ms | 1.4536ms |
| Large array | 0.5859ms | 0.2391ms |
| Large identical arrays | 0.0919ms | 0.0031ms |
| Simple object | 0.0003ms | 0.0002ms |
About 55% faster on average, and ~97% faster when the two inputs are identical, which is the common case when you are diffing state on every update. Full table.
Next
- Every option and the full
Differencetype:@blazediff/objectreference - Comparing images instead: Introduction