structuredClone instead of JSON.parse + JSON.stringify
tl;dr: To deep clone objects, Use structuredClone(value)
rather than the JSON.parse(JSON.stringify(value))
trick. Also, avoid Lodash’s _.cloneDeep(value)
due to import cost.
const tmp = {};
// Generates random properties with random values;
for (let i = 0; i < 100; ++i) {
const prop = (Math.random() + 1).toString(36);
const value = (Math.random() + 1).toString(36);
tmp[prop] = value;
}
console.log(tmp);
// Benchmarks `JSON.parse(JSON.stringify(tmp))`.
const t0 = performance.now();
for (let i = 0; i < 1e3; ++i) {
const cloned = JSON.parse(JSON.stringify(tmp));
}
const t1 = performance.now();
console.log("JSON.parse(JSON.stringify(tmp))", t1 - t0, "ms");
// Benchmarks `structuredClone(tmp)`.
const t2 = performance.now();
for (let i = 0; i < 1e3; ++i) {
const cloned = structuredClone(tmp);
}
const t3 = performance.now();
console.log("structuredClone(tmp)", t3 - t2, "ms");
{1.1s3gdhnpqv: '1.qm4ut6i7y8', 1.9etzo6na83f: '1.oyba5gqfi1l', 1.8evlhbw2jh: '1.hud1cld83w', 1.zauu71t302: '1.ism0tme9fm', 1.n0edgtt1wq: '1.0tjxfdr6u2', ...}
JSON.parse(JSON.stringify(tmp)) 30.700000002980232 ms
structuredClone(tmp) 21.400000005960464 ms
As you can see, structuredClone(tmp)
is faster than JSON.parse(JSON.stringify(tmp))
by about (30 - 21) / 30 * 100 = 30%
.