<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
function createObj() {
return {
description: 'Creates a deep copy of source, which should be an object or an array.',
myNumber: 123456789,
myBoolean: true,
date: new Date(),
date1: new Date(),
date2: new Date(),
date3: new Date(),
jayson: {
stringify: 'JSON.stringify() method converts a JavaScript value to a JSON string....',
parse: 'JSON.parse() method parses a JSON string...',
date: new Date(),
date1: new Date(),
date2: new Date(),
date3: new Date()
}
}
}
var MyObject = [];
for (let i = 0; i++; i<=500) {
MyObject.push(createObj());
}
var myCopy = null;
myCopy = _.cloneDeep(MyObject);
myCopy = JSON.parse(JSON.stringify(MyObject));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Json clone |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 555560.1 Ops/sec |
Json clone | 409924.6 Ops/sec |
Let's break down the provided benchmark.
Benchmark Overview
The benchmark compares the performance of two methods for creating a deep copy of an object: Lodash's cloneDeep
and the built-in JSON.parse(JSON.stringify())
method.
Test Case 1: Lodash cloneDeep
MyObject
containing 500 copies of an object with nested properties, including dates.cloneDeep
function to create a deep copy of MyObject
.Pros and Cons of Lodash cloneDeep
Test Case 2: JSON Clone
MyObject
containing 500 copies of an object with nested properties, including dates.JSON.parse(JSON.stringify())
method to create a deep copy of MyObject
.Pros and Cons of JSON Clone
Library Used: Lodash.js
Lodash is a popular JavaScript utility library that provides a wide range of functions for tasks such as array manipulation, object manipulation, and more. In this benchmark, cloneDeep
is used to create deep copies of objects.
Special JS Feature/ Syntax: None
Neither test case uses any special JavaScript features or syntax.
Other Considerations
cloneDeep
.Alternative Methods
Other alternatives for creating deep copies of objects include:
Object.assign(null, object)
(a workaround for older versions of Internet Explorer)Array.prototype.slice.call(object)
(only works with arrays)Keep in mind that each method has its trade-offs and use cases. Lodash's cloneDeep
is often considered the best choice for creating deep copies of objects, but may require additional overhead due to the external library.