<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 = arr.slice(0)
var myCopy = Object.assign([], arr)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Lodash clone | |
Array.slice() | |
Array.slice(0) | |
Object.assign() |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 400338.3 Ops/sec |
Lodash clone | 2312363.2 Ops/sec |
Array.slice() | 7494326.5 Ops/sec |
Array.slice(0) | 7599966.0 Ops/sec |
Object.assign() | 537148.8 Ops/sec |
Let's break down the provided benchmark and explain what is tested, the options compared, their pros and cons, and other considerations.
Benchmark Definition
The benchmark is to compare the performance of creating shallow copies of an array using different methods: Lodash cloneDeep
, Lodash clone
, Array.slice()
, Array.slice(0)
, and Object.assign()
.
Options Compared
cloneDeep
: A deep copy of an object or array, which creates a new, independent copy of the original data structure.clone
: A shallow copy of an object or array, which creates a new copy of only the top-level properties and does not recursively clone nested objects or arrays.Array.slice()
: Creates a new array containing a subset of elements from the original array, starting at the specified index (0).Array.slice(0)
: Similar to Array.slice()
, but starts at index 0 and returns a shallow copy of the entire array.Object.assign()
: Copies the values of all enumerable own properties from one or more source objects to a target object.Pros and Cons
cloneDeep
:clone
:cloneDeep
, as it only creates a new copy of top-level properties and does not recursively clone nested objects or arrays.Array.slice()
:Array.slice(0)
:Array.slice()
, but starts at index 0 and returns a shallow copy of the entire array.Object.assign()
:Other Considerations
cloneDeep
provides the former, while clone
and Object.assign()
provide the latter.Alternatives
If you're looking for alternatives to Lodash or its methods, consider the following:
JSON.parse(JSON.stringify())
: Creates a deep copy of an object by parsing the JSON representation of the original object and then stringifying it again.lodash-es
: An ES module version of Lodash, which can provide similar functionality to cloneDeep
, clone
, etc.immer
: A library that provides a functional programming approach to working with data structures, including creating immutable copies.These alternatives may offer different trade-offs in terms of performance, complexity, or feature set, so it's essential to evaluate them based on your specific use case and requirements.