<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 = { o }
const a = Object.assign({}, o)
const a = JSON.parse(JSON.stringify(o))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash clone | |
ES6 spread | |
ES6 Object.assign | |
Json |
Test name | Executions per second |
---|---|
Lodash clone | 966533.2 Ops/sec |
ES6 spread | 7931643.0 Ops/sec |
ES6 Object.assign | 2437830.5 Ops/sec |
Json | 240839.7 Ops/sec |
Let's break down what's being tested in the provided benchmark.
Benchmark Definition
The benchmark measures the performance of different approaches for creating a deep clone of an object. The test case uses a sample object o
with nested properties and arrays, which is then cloned using four different methods:
_clone()
function from the Lodash library to create a deep copy of the object.{ ...o }
to create a shallow copy of the object (not suitable for deep cloning).Object.assign()
method with an empty object as the target to create a shallow copy of the object (not suitable for deep cloning).JSON.parse(JSON.stringify(o))
to create a deep clone of the object.Library and Syntax
{ ...o }
) is a shorthand syntax for creating a new object with all the properties of o
. While it can be useful for shallow cloning, it doesn't work well for deep cloning due to issues like circular references.Pros and Cons
Here's a brief summary of each approach:
Other Considerations
When choosing a method for deep cloning an object, consider the following factors:
Alternatives
If you don't want to use Lodash, you could explore other libraries like:
lodash-deep-clone
or deep-clone
: Specialized deep cloning libraries that are smaller and faster than Lodash.JSON.parse(JSON.stringify())
with a custom implementation for handling circular references.Keep in mind that these alternatives might have different trade-offs in terms of performance, code readability, and library dependencies.