<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...'
}
};
function deepClone(preObj) {
let newObj, value, key;
if (typeof preObj !== "object" || preObj === null) {
return preObj;
}
newObj = Array.isArray(preObj) ? [] : {}
for (key in preObj) {
value = preObj[key];
newObj[key] = deepClone(value);
}
return newObj
}
var myCopy = null;
myCopy = _.cloneDeep(MyObject);
myCopy = JSON.parse(JSON.stringify(MyObject));
deepClone(MyObject)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Json clone | |
Fast deep clone |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 718782.2 Ops/sec |
Json clone | 618543.6 Ops/sec |
Fast deep clone | 3291662.0 Ops/sec |
Let's break down the provided benchmark and explain what is being tested, compared, and their pros and cons.
Benchmark Test Cases
The test cases compare three different approaches to create a deep copy of an object: Lodash cloneDeep
, JSON Clone
, and Fast deep clone
.
lodash
library's cloneDeep
function to create a deep copy of the object.JSON.stringify()
method to serialize the object, convert it back to a JSON string using JSON.parse()
, and then parse the resulting string back into an object.deepClone
that creates a new object with the same properties as the original object.Comparison
The test cases measure the execution time of each approach on the provided object, which contains nested objects and arrays.
Pros and Cons
lodash
).Library Explanation
The lodash
library is a popular JavaScript utility library that provides a wide range of functions for tasks such as string manipulation, array and object manipulation, and more. The cloneDeep
function in particular is designed to create deep copies of complex data structures, making it efficient and convenient for this benchmark.
Special JS Feature or Syntax
The test case uses the let
keyword with the const
property, which is a shorthand way of declaring variables in JavaScript. This syntax is supported in modern browsers and Node.js environments.
Other Alternatives
For creating deep copies of objects, other alternatives include:
These alternatives may have different trade-offs in terms of performance, memory usage, or complexity, depending on the specific use case.