<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.stringify(MyObject)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash CloneDeep | |
Json Clone |
Test name | Executions per second |
---|---|
Lodash CloneDeep | 346864.4 Ops/sec |
Json Clone | 432711.2 Ops/sec |
What is being tested?
The provided JSON represents two individual test cases for measuring the performance of cloning an object in JavaScript. The first test case, "Json Clone", tests the JSON.stringify()
method to create a clone of the object MyObject
. The second test case, "Lodash CloneDeep", uses the _cloneDeep()
function from the Lodash library to create a deep copy of MyObject
.
What options are being compared?
The two options being compared are:
Pros and Cons of each approach:
JSON.stringify()
:_cloneDeep()
function:JSON.stringify()
.Library used in the test case
The test case uses the Lodash library, which is a popular utility library for JavaScript. The _cloneDeep()
function is part of the Lodash collection and provides a simple way to create deep copies of objects.
Special JS feature or syntax
None are mentioned in this specific benchmark definition.
Benchmark preparation code explanation
The script preparation code defines an object MyObject
with various properties, including a nested object jayson
. The recursiveDeepCopy()
function is defined to recursively clone the object. The Html Preparation Code includes a link to the Lodash library, which is required for the _cloneDeep()
function.
Other alternatives
Some alternative methods for creating deep copies of objects in JavaScript include:
{...o}
) or Object.assign()
However, these methods may not provide the same level of performance or property preservation as the Lodash _cloneDeep()
function.