<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var MyObject = {
string: 'Creates a deep copy of source, which should be an object or an array.',
number: 1234567890,
boolean: true,
nullable: null,
json: {
stringify: 'JSON.stringify() method converts a JavaScript value to a JSON string....',
parse: 'JSON.parse() method parses a JSON string...'
},
array: [
{
id: 5,
blocked: false,
avatar: null,
user: {
firstName: 'Alan',
lastName: 'Walker'
},
},
{
id: 5688,
blocked: false,
avatar: null,
user: {
firstName: 'Anna',
lastName: 'Wanderwood'
},
},
{
id: 80043,
blocked: true,
avatar: 'image.jpg',
user: {
firstName: 'Serj',
lastName: 'Cooper'
},
},
]
};
var myCopy = null;
myCopy = _.cloneDeep(MyObject);
myCopy = JSON.parse(JSON.stringify(MyObject));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Json clone |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 386460.7 Ops/sec |
Json clone | 455773.6 Ops/sec |
Measuring JavaScript performance is a complex task, and MeasuratThat.net provides a valuable platform for comparing different approaches.
Benchmark Definition
The provided benchmark compares the execution times of two methods to create a deep copy of an object:
_.cloneDeep(MyObject)
(Lodash cloneDeep)JSON.parse(JSON.stringify(MyObject))
(JSON clone)Comparison of options
Both methods are used to create a deep copy of the input object, but they have different approaches.
JSON.stringify()
and JSON.parse()
to serialize the object to a string, which is then parsed back into an object. This approach can create a shallow copy, which may not work as expected for deeply nested objects.Other considerations
JSON clone
may be sufficient. However, for more complex objects, Lodash cloneDeep
is recommended.Library and purpose
cloneDeep()
method.Special JS feature or syntax
None mentioned. Both methods are standard JavaScript approaches.
Alternatives
Other alternatives for creating deep copies of objects include:
immer
or copy-deep
deepcopy
Keep in mind that the choice of method depends on your specific use case, performance requirements, and personal preference.