Good news: You can deep clone objects in the browser via structuredClone


Good news: You can deep clone objects in the browser via structuredClone! ๐ŸŽ‰

Bad news: Spread syntax is 34x faster than stucturedClone. โš ๏ธ

structuredClone: 467k/sec
spread: 15.9m/sec

Solution: When you need to do a deep clone of a nested object, use structuredClone. (this should be rare). Otherwise, continue to use spread syntax. It's much more efficient.

I dug into this because I'm working in a project where structuredClone is being needlessly used by default instead of spread.

Don't do this. It's wasteful.

Consider structuredClone a power tool for rare cases.

Benchmark: https://www.measurethat.net/Benchmarks/Show/24324/0/structuredclone-vs-spread-syntaxhttps://www.measurethat.net/Benchmarks/Show/24324/0/structuredclone-vs-spread-syntax
To be clear:

Spread syntax and Object.assign only do a shallow clone. So if you pass them a nested object, the nested object will not be cloned.

Thatโ€™s why structuredClone was created. It does a deep clone. (It clones child objects too.)

But, structuredClone is slower. So only use it when you need to do a deep clone.

View original on X