<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(x) {
if (x === null || typeof x !== 'object') return x;
if (Array.isArray(x)) return x.map((item) => deepClone(item));
return Object.fromEntries(
Object.entries(x).map(([key, value]) => [key, deepClone(value)])
);
};
var myCopy = null;
myCopy = _.cloneDeep(MyObject);
myCopy = structuredClone(MyObject);
myCopy = deepClone(MyObject);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Native structuredClone | |
Custom Deep Clone |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 1551654.1 Ops/sec |
Native structuredClone | 585555.0 Ops/sec |
Custom Deep Clone | 865775.9 Ops/sec |
Let's break down the benchmark and analyze what's being tested, compared options, pros and cons of each approach, and other considerations.
Benchmark Definition
The benchmark measures the performance of three approaches for creating a deep copy of an object:
cloneDeep
function from the Lodash library.structuredClone
API introduced in modern JavaScript (ES2020) to create a deep copy.deepClone
, for creating a deep copy.Comparison
The three approaches are being compared in terms of their performance. The benchmark prepares a sample object (MyObject
) and then creates a deep copy of it using each approach. The test measures the number of executions per second (ExecutionsPerSecond) for each approach, which indicates how fast each method can create multiple copies.
Options
Here's an overview of each option:
cloneDeep
function from Lodash to create a deep copy. This is a widely-used library that provides a variety of utility functions, including deep cloning.structuredClone
API introduced in modern JavaScript (ES2020) to create a deep copy. This is a relatively new feature that provides a lightweight and efficient way to clone objects.deepClone
) for creating a deep copy. This approach requires manual implementation of the cloning logic.Library
cloneDeep
function is one of its many utility functions.Special JS Feature/Syntax
The benchmark uses the structuredClone
API, which is a relatively new feature introduced in modern JavaScript (ES2020). This API provides a lightweight and efficient way to clone objects.
Other Considerations
When choosing an approach for creating deep copies, consider factors such as:
Alternatives
If you're looking for alternatives to these approaches, consider: