<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;
myCopy = _.cloneDeep(MyObject);
myCopy = structuredClone(MyObject);
myCopy = JSON.parse(JSON.stringify(MyObject))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Native structuredClone | |
JSON String parse |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 527488.1 Ops/sec |
Native structuredClone | 211043.8 Ops/sec |
JSON String parse | 298135.6 Ops/sec |
Let's break down the benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Overview
The benchmark compares three methods to create a deep copy of an object: _.cloneDeep
from Lodash, structuredClone
(a native JavaScript method introduced in ES2022), and JSON.parse(JSON.stringify(MyObject))
.
Test Cases
_.cloneDeep
function from Lodash to create a deep copy of the MyObject
. _
is an alias for the Lodash library, which provides utility functions for functional programming.structuredClone
method (introduced in ES2022) to create a deep copy of the MyObject
.JSON.parse(JSON.stringify(MyObject))
syntax to create a deep copy of the MyObject
. Note that this method does not support cyclic references, which can lead to incorrect results.Comparison
The benchmark compares the performance of these three methods across different browsers and execution rates. The results show that:
_.cloneDeep
is generally faster than the native structuredClone
method.JSON String parse
method is slower and less reliable, especially with large input sizes.Pros and Cons
Other Considerations
structuredClone
method is designed to work with structured data formats like JSON and XML. It's optimized for performance and safety, but might not be suitable for all use cases._.cloneDeep
is a well-maintained and widely adopted solution, but it may have performance overhead due to its complexity.Alternatives
If you don't want to use Lodash or rely on the native structuredClone
method, you can consider:
Keep in mind that these alternatives may introduce additional complexity and performance overhead.
I hope this explanation helps!