<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var MyObject = {
description: 'Creates a deep copy of source, which should be an object or an array.',
myNumber: 123456789,
myBoolean: true,
jayson: {
stringify: 'JSON.stringify() method converts a JavaScript value to a JSON string....',
parse: 'JSON.parse() method parses a JSON string...',
jayson: {
stringify: 'JSON.stringify() method converts a JavaScript value to a JSON string....',
parse: 'JSON.parse() method parses a JSON string...',
jayson: {
stringify: 'JSON.stringify() method converts a JavaScript value to a JSON string....',
parse: 'JSON.parse() method parses a JSON string...',
jayson: {
stringify: 'JSON.stringify() method converts a JavaScript value to a JSON string....',
parse: 'JSON.parse() method parses a JSON string...'
}
}
}
}
};
var arr = []
for (let i = 0; i <=10000; i++) {
arr.push(structuredClone(MyObject))
}
var myCopy = null;
myCopy = _.cloneDeep(arr);
myCopy = structuredClone(arr);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Native structuredClone |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 23.6 Ops/sec |
Native structuredClone | 23.2 Ops/sec |
Let's break down the benchmark and its options.
Benchmark Definition
The benchmark compares two approaches to create a deep copy of an array:
cloneDeep
function from the Lodash library, which is a popular utility library for JavaScript.structuredClone
API, which is a relatively new feature introduced in ECMAScript 2020.Options Compared
The two options are compared in terms of their performance on creating a deep copy of an array with 10,000 elements.
Pros and Cons
Other Considerations
structuredClone
API uses the JSON
protocol to create deep copies, which is a relatively new feature introduced in ECMAScript 2020.Alternative Approaches
Other approaches to creating deep copies include:
JSON.parse()
to create a deep copy, although this can be slower and more memory-intensive than structuredClone
.Keep in mind that the best approach depends on the specific requirements and constraints of your project.