var arr = [{value: 0},{value: 1}, {value: 2}, {value: 3}, {value: 4}, {value: 5}, {value: 6}]
JSON.parse(JSON.stringify(arr))
_.cloneDeep(arr)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON clone | |
loadash clone |
Test name | Executions per second |
---|---|
JSON clone | 843098.6 Ops/sec |
loadash clone | 538702.2 Ops/sec |
Let's break down what is tested in the provided JSON benchmark.
Script Preparation Code
The script preparation code defines an array arr
containing six objects with a single property value
. This array will be used as the input for the benchmarks.
Benchmark Definitions There are two benchmark definitions:
JSON.parse(JSON.stringify(arr))
method to create a deep clone of the arr
array._.cloneDeep(arr)
function to create a deep clone of the arr
array.Library: Lodash
The Lodash library is a popular JavaScript utility library that provides various functions for tasks such as array manipulation, object transformation, and more. In this case, the _
object represents the Lodash library, and the .cloneDeep()
method is used to create a deep clone of the input array.
Special JS Feature or Syntax Neither of the benchmark definitions uses any special JavaScript features or syntax. They only rely on standard JavaScript methods and libraries.
Comparison of Options
JSON.parse(JSON.stringify(arr))
method is a simple and widely supported way to create a deep clone of an object. However, it can be slower than the Lodash clone because it involves parsing and stringifying the entire input array._.cloneDeep()
method is designed specifically for creating deep clones of complex data structures like arrays. It is often faster and more efficient than the built-in JSON clone method.Pros and Cons
Other Alternatives
If you need to create a deep clone of an array without using the JSON.parse(JSON.stringify(arr))
method or Lodash, you can also use other libraries like:
_cloneDeep()
method.Alternatively, you can implement your own deep clone function using recursion and iteration. However, this approach may be more error-prone and less efficient than using an existing library like Lodash or FastClone.