In the previous post, I reviewed 3 ways of cloning an object:
- Spread operator
- JSON stringify
- Lodash cloneDeep
I did a quick benchmark to compare the performance of these 3 methods, with the help of my mini app js-benchmarks.
I first build 3 objects of different complexities:
const object1 = { id: 1, value: 'simpleObject', age: 24, name: 'Im just a simple objects with strings and numbers' }; const object2 = { value: 'mediumObject', date: new Date(), nestedObject: { hello: 'prop1', hi: new Date() }, cb: () => console.log('hello') }; const object3 = { value: 'bigObject', bigArray: [ object2, object2, object2, object2, object2, object2, object2, object2, object2, object2, object2, object2, object2, object2, object2, object2, object2, object2, object2, object2, object2, object2, object2, object2 ] };
Then, for each method, I repeat the execution a thousand times for each object, and I get the average execution time (refer to my previous performance comparison post for more details).
Here are the results (shown in ms):
Here are some highlights:
- Spread operator method is the fastest, but keep in mind that it is not recursive, no it may not be the right choice depending on the situation.
- JSON.stringify can be a good choice when the object to clone is not too big, otherwise the execution time can quickly explode (also be careful of the data type in the object properties to make sure that JSON stringify can correctly clone it).
- cloneDeep de lodash should be used carefully, and only when the object to clone needs a complex recursive algorithm. because the execution time is not light.