<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 = JSON.parse(JSON.stringify(o))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash clone | |
Lodash cloneDeep | |
Lodash merge | |
ES6 spread | |
ES6 Object.assign | |
JSON Parse |
Test name | Executions per second |
---|---|
Lodash clone | 1517064.5 Ops/sec |
Lodash cloneDeep | 246622.0 Ops/sec |
Lodash merge | 168033.8 Ops/sec |
ES6 spread | 13576210.0 Ops/sec |
ES6 Object.assign | 3868648.0 Ops/sec |
JSON Parse | 437533.2 Ops/sec |
Measuring the performance of different JavaScript methods for object cloning and manipulation is essential to ensure efficient code execution.
The provided JSON represents a benchmark with six test cases, each testing a distinct approach:
_.clone()
method from Lodash, a popular utility library that provides functional programming helpers._.cloneDeep()
method from Lodash, designed to create an exact deep copy of the source object._.merge()
method from Lodash, which merges multiple sources into a single target object.{ ...o }
(spread operator) to create a shallow copy of the source object.Object.assign()
method to merge the source object with a new target object.JSON.parse(JSON.stringify(o))
, a trick that uses JSON serialization and deserialization to create an exact deep copy of the source object.Now, let's discuss the pros and cons of each approach:
Pros and Cons:
_.clone()
and _.cloneDeep
, this method provides a simple way to merge objects but may not be the most efficient solution._.merge()
from Lodash, it's simple but may not provide the most efficient solution.Alternative approaches:
Other methods you can use for object cloning include:
Keep in mind that each method has its strengths and weaknesses, and choosing the best approach depends on your specific use case and performance requirements.