If you're using a schema library, you can derive a jit-compiled deep equals function that's ~5-10 times faster than fast-deep-equal
, and ~70-80x faster than Lodash (or any other recursive solution).
// also supported: JSON Schema, TypeBox, ArkType, valibot
import { deepEqual } from '@traversable/zod'
const myEqualsFn = deepEqual(z.array(z.object({ name: z.string(), age: z.number() })))
myEqualsFn(
[
{'name': 'john', 'age': 22},
{'name': 'mike', 'age': 20},
],
[
{'name': 'john', 'age': 22},
{'name': 'mike', 'age': 42}
]
)
// => false
Run / play with the benchmarks here: https://bolt.new/~/mitata-k7dj9raq
This works because we're able to use the schema to optimize the comparison.
I wrote a short blog post that goes into more detail here: https://dev.to/ahrjarrett/how-i-built-javascripts-fastest-deep-equals-function-51n8
Edit: forgot to include a link, the library is here: https://github.com/traversable/schema/