<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js'></script>
arr = [];
for (let i = 0; i < 200; i += 1) {
arr.push({
name: `Person${i}`,
birthday: moment().add(i, 'days').toDate(),
});
}
const cloneArr = _.cloneDeep(arr);
const cloneArr = JSON.parse(JSON.stringify(arr));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Deep clone with JSON.parse(JSON.stringify(obj)) |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 4115.1 Ops/sec |
Deep clone with JSON.parse(JSON.stringify(obj)) | 5739.2 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Overview
The benchmark compares two approaches for creating a deep clone of an object: Lodash's cloneDeep
function and using JSON.parse(JSON.stringify(obj))
. The test creates an array of objects with nested properties, including dates, to simulate real-world data structures.
Options Compared
Two options are compared:
_.cloneDeep()
method from Lodash, a popular JavaScript utility library. It recursively clones the entire object graph, ensuring that all nested properties are also cloned.JSON.parse()
method to convert the original object into a JSON string and then parses it back into an object using JSON.parse()
. While this method can create a shallow clone, it's not suitable for deep cloning objects with complex nested structures.Pros and Cons
Lodash cloneDeep
Pros:
Cons:
JSON.parse(JSON.stringify(obj))
Pros: None.
Cons:
cloneDeep
.Library: Lodash
Lodash is a popular JavaScript utility library that provides various functions for tasks such as array manipulation, string iteration, and object cloning. The cloneDeep()
function is specifically designed for deep cloning objects and has become a de facto standard in the JavaScript community.
Special JS Feature or Syntax (None)
There are no special JavaScript features or syntax used in this benchmark.
Alternative Approaches
Other approaches for creating deep clones of objects include:
Object.assign()
method with an empty object: const cloneObj = Object.assign({}, originalObj);
js-yaml
or deepclone
that provide similar functionality to Lodash's cloneDeep
.However, these approaches may have their own trade-offs and limitations, making the comparison between Lodash's cloneDeep
and JSON.parse(JSON.stringify(obj))
still relevant for understanding performance and code readability considerations.