<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var o = {
a: {
b: 1,
c: 2,
d: 3,
j: {
k: [1,2,3],
l: [4,5,6]
},
},
e: [1,2,3,4,5,6],
f: 1,
g: {
h: 1,
}
}
const a = _.clone(o)
const a = _.cloneDeep(o)
const a = _.merge({}, o)
const a = { o }
const a = Object.assign({}, o)
const a = structuredClone(o)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash clone | |
Lodash cloneDeep | |
Lodash merge | |
ES6 spread | |
ES6 Object.assign | |
ES6 structuredClone |
Test name | Executions per second |
---|---|
Lodash clone | 1436456.2 Ops/sec |
Lodash cloneDeep | 235764.4 Ops/sec |
Lodash merge | 147443.3 Ops/sec |
ES6 spread | 12428702.0 Ops/sec |
ES6 Object.assign | 3618760.8 Ops/sec |
ES6 structuredClone | 198469.6 Ops/sec |
Let's dive into the provided benchmark.
What is being tested?
The benchmark tests six different methods for creating a shallow copy of an object:
clone()
methodcloneDeep()
method (which creates a deep copy)merge()
{ ...o }
)Object.assign()
to create a shallow copystructuredClone()
(a relatively new feature introduced in ECMAScript 2022)Options being compared:
Each method has its own strengths and weaknesses.
clone()
: This method creates a shallow copy of the object, which means it only copies the top-level properties. It's faster than cloneDeep()
, but may not be suitable for deeply nested objects.cloneDeep()
: This method creates a deep copy of the object, which means it recursively copies all properties and their values. It's slower than clone()
, but ensures that the copied object is fully independent from the original.merge()
: This approach can be useful when you want to create a new object by copying the properties from an existing object, while preserving any additional properties on the target object. However, it may not be suitable for all use cases.{ ...o }
): This method creates a shallow copy of the object by spreading its top-level properties into a new object. It's concise and easy to read, but only copies the top-level properties.Object.assign()
: This method creates a shallow copy of the object by assigning its values to a new object. It's similar to clone()
, but may be slower due to the overhead of function calls.structuredClone()
: This is a relatively new feature that creates a deep copy of an object, while also preserving any metadata associated with the original object. It's still experimental and might not be supported by all browsers.Pros and Cons:
Here are some pros and cons for each method:
clone()
: Fast, but only copies top-level properties.cloneDeep()
: Slower, creates a deep copy of the object.merge()
:{ ...o }
):Object.assign()
:clone()
, but may be faster due to reduced overhead.structuredClone()
:Libraries and special features:
I hope this explanation helps you understand the benchmark results!