<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js'></script>
var arr = ['one', 'two', 'three', {four: 'five'}];
var myCopy = _.cloneDeep(arr)
var myCopy = _.clone(arr)
var myCopy = arr.slice()
var myCopy = Object.assign([], arr)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Lodash clone | |
Array.slice() | |
Object.assign() |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 797923.4 Ops/sec |
Lodash clone | 14214869.0 Ops/sec |
Array.slice() | 35121972.0 Ops/sec |
Object.assign() | 853114.2 Ops/sec |
Let's break down the provided JSON and explain what is tested, the options compared, their pros and cons, and other considerations.
What is being tested?
The benchmark measures the performance difference between four methods to create a shallow copy of an array: Lodash cloneDeep
, Lodash clone
, Array slice()
, and Object assign()
.
Options compared:
cloneDeep
: Creates a deep copy of the original object, which means all nested properties are recursively cloned.clone
: Creates a shallow copy of the original object, which means only the top-level properties are copied and not any nested objects.slice()
: Returns a new array that contains a subset of elements from the original array, without modifying the original array.assign()
: Returns a new object that is a shallow copy of the original object, which means only the top-level properties are copied and not any nested objects.Pros and Cons:
cloneDeep
: Pros:clone
: Pros:cloneDeep
since it only copies top-level properties.slice()
: Pros:assign()
: Pros:Library used:
The benchmark uses Lodash (a popular JavaScript utility library) for its cloneDeep
and clone
functions. The assign
method is built-in to JavaScript.
Special JS features or syntax:
None mentioned in the provided JSON, but it's worth noting that Lodash cloneDeep
uses a recursive function to clone objects, which might be slower than other methods for very large data structures.
Alternatives:
Other alternatives to create a shallow copy of an array or object include:
...
) in JavaScript (available from ES6 onwards): const myCopy = [...arr];
or const myCopy = { ...obj };
JSON.parse(JSON.stringify(obj))
.Keep in mind that the performance differences between these alternatives may vary depending on the specific use case and data structure.