2 ms·
I've wondered about that with JSON.parse(JSON.stringify(obj)) being the fastest way to deep clone a plain JS object in any JS engine. It always looks dumb when
by WorldMaker 7y ago
I've wondered about that with JSON.parse(JSON.stringify(obj)) being the fastest way to deep clone a plain JS object in any JS engine. It always looks dumb when it shows up, but it works well enough and I've seen it described as a best practice by some types of data manipulation libraries.
- vorticalbox 7y agoWould like to know this aswell. I know using spread const clone = {...source}; Is faster than object.assign({},source) And seeing as in this case the source is already a js object it would probably be slow to string and the parse.
- WorldMaker 7y agoKeep in mind that both of those two options are only shallow clones. If you've got any bit of nesting and need a deep clone the code starts to get a lot more complex. In general, in places where I "need" a lot of deep clones I try to use an Immutable library with good reuse/sharing tools, but when you have to deep clone a plain JS object JSON.parse(JSON.stringify(obj)) is incredibly fast in most browsers, despite the fact that you would think string allocation might be a bottle neck.