<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var MyObject = {
description: 'Creates a deep copy of source, which should be an object or an array.',
myNumber: 123456789,
myBoolean: true,
jayson: {
stringify: 'JSON.stringify() method converts a JavaScript value to a JSON string....',
parse: 'JSON.parse() method parses a JSON string...'
}
};
var myCopy = null;
function recursiveDeepCopy(o) {
var newO,
i;
if (typeof o !== 'object') {
return o;
}
if (!o) {
return o;
}
if ('[object Array]' === Object.prototype.toString.apply(o)) {
newO = [];
for (i = 0; i < o.length; i += 1) {
newO[i] = recursiveDeepCopy(o[i]);
}
return newO;
}
newO = {};
for (i in o) {
if (o.hasOwnProperty(i)) {
newO[i] = recursiveDeepCopy(o[i]);
}
}
return newO;
}
myCopy = _.cloneDeep(MyObject);
myCopy = JSON.parse(JSON.stringify(MyObject));
myCopy = recursiveDeepCopy(MyObject);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash CloneDeep | |
Json Clone | |
recursiveDeepCopy |
Test name | Executions per second |
---|---|
Lodash CloneDeep | 1907430.2 Ops/sec |
Json Clone | 1564660.4 Ops/sec |
recursiveDeepCopy | 5923260.5 Ops/sec |
Let's dive into the benchmark and explain what is being tested.
The provided JSON represents a JavaScript microbenchmark that compares three approaches for creating a deep copy of an object: lodash.cloneDeep
, JSON.parse(JSON.stringify())
, and a custom recursive function called recursiveDeepCopy
.
Test Case 1: Lodash CloneDeep
cloneDeep
function creates a deep copy of an object, which means it recursively copies all properties and nested objects.Test Case 2: JSON.parse(JSON.stringify())
JSON.parse()
function to parse a JSON string, which creates a deep copy of an object. The JSON.stringify()
function is used to convert an object to a JSON string.Test Case 3: recursiveDeepCopy
Other alternatives to consider:
Keep in mind that each approach has its trade-offs, and the best choice depends on your specific use case, performance requirements, and code readability concerns.