DEV Community

Discussion on: Copying Javascript Objects in an efficient way

Collapse
 
einperegrin profile image
Roman Sokolov

Thanks for the post.
Using lodash is not an efficient way, it's just the simplest way. Weight of lodash is 71k (24,7 gzipped), isn't too much for one function? A little better could be an import of just this function, but real efficiently is using own realizations.

import _ from 'lodash; // 71k (24,7k gzipped)
import cloneDeep from 'lodash/cloneDeep'; // 17,4k (4,8k) - it's still too much

let copyData = JSON.parse(JSON.stringify(data)) // how much? 32 bytes!
Enter fullscreen mode Exit fullscreen mode

By the way, JSON.parse(JSON.stringify) is the most efficient way in JS to deep clone an object.

Collapse
 
einperegrin profile image
Roman Sokolov

But of course, this way is more dangerous because it doesn't have any checkings and if you want to use it, you have to add checking at least for recursive links.

Collapse
 
ganeshmani profile image
GaneshMani

By doing json serialization, you will lose any Javascript property that has no equivalent type in JSON, like Function or Infinity. Any property that’s assigned to undefined will be ignored by JSON.stringify, causing them to be missed on the cloned object.

Collapse
 
einperegrin profile image
Roman Sokolov

Yes, I agree with you. And I've noticed it in the comment below. But there are no functions or Infinity in your example, thus this way is the most efficient for objects like this.
For complicated objects, it's safer (safer, not faster) to use some custom realizations or even cloneDeep from lodash/cloneDeep (or just package 'lodash.cloneDeep'). But there are no reasons to pull the whole lodash library if you don't want to use all of its methods. It just inflates your bundle size.
So, let's come to a consensus: it’s good when you know your data and tools and select the tools suitable for the data and tasks :-)