<script src='https://cdn.jsdelivr.net/npm/lodash@4.17.21/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...'
}
};
myCopy = _.cloneDeep(MyObject);
myCopy = JSON.parse(JSON.stringify(MyObject));
myCopy = structuredClone(MyObject)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash CloneDeep | |
JSON Clone | |
structuredClone |
Test name | Executions per second |
---|---|
Lodash CloneDeep | 1472396.4 Ops/sec |
JSON Clone | 1215980.4 Ops/sec |
structuredClone | 685871.8 Ops/sec |
Overview of the Benchmark
The provided benchmark compares three methods for creating a deep copy of an object: Lodash's cloneDeep
, JSON's parse
and stringify
methods, and the structuredClone
function.
What is being tested?
In this benchmark, we're testing the performance of each method in creating a deep copy of a complex object with nested properties. The object includes an array, a boolean, and another object with its own properties.
Options Compared:
cloneDeep
function to create a deep copy of the original object.parse
and stringify
methods to create a deep copy of the original object. This involves converting the object to a JSON string, parsing it back into an object, and then cloning it.structuredClone
function (introduced in ECMAScript 2020) to create a deep copy of the original object.Pros and Cons:
Library Used:
In this benchmark, Lodash is used as a dependency for the cloneDeep
function.
Special JS Feature/Syntax:
The structuredClone
function is a new feature introduced in ECMAScript 2020. It's designed to create a deep copy of an object without using any external dependencies or modifying the original object.
Benchmark Preparation Code Explanation:
The script preparation code defines an object MyObject
with nested properties, including an array and a boolean. The HTML preparation code includes a link to the Lodash library for use in the benchmark.
Individual Test Cases:
Each test case uses a different method to create a deep copy of the original object:
_.cloneDeep(MyObject)
to create a deep copy.JSON.parse(JSON.stringify(MyObject))
to create a deep copy.structuredClone(MyObject)
to create a deep copy.Other Alternatives:
If you need to compare other methods for creating deep copies, some alternatives could be:
Object.assign()
with the spread operator (...
) to create a shallow copy, and then using Object.assign()
again to create a deep copy.However, these alternatives are not part of the benchmark being discussed.