<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...'
},
abc: {
test: [1, 2, 3],
other: []
}
};
var myCopy = null;
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 | 237073.6 Ops/sec |
Json clone | 318683.0 Ops/sec |
structuredClone | 288438.0 Ops/sec |
Let's break down the benchmark and its test cases.
Benchmark Overview
The benchmark measures the performance of three different methods to create a deep copy of an object: _.cloneDeep
from Lodash, JSON.parse(JSON.stringify())
, and structuredClone
. The test case uses a sample object MyObject
with various properties, including nested objects and arrays.
Test Cases
_.cloneDeep()
function from Lodash.JSON.parse(JSON.stringify())
trick to create a deep copy of the input object. This approach converts the object to a JSON string, then parses it back into an object.structuredClone()
function.Pros and Cons
Library and Features
cloneDeep()
. It's widely used and well-maintained.Special JS Features or Syntax
None mentioned explicitly in the benchmark, but note that structuredClone()
relies on the Structured Clone
proposal, which is still a work in progress. If you're interested in exploring this feature further, I can provide more information!
Other Alternatives
If you're not using Lodash or want to explore other options, here are some additional deep copying methods:
eval()
to create a new object from the string. Be cautious with this method as it can lead to security issues if used incorrectly.Keep in mind that these alternatives may not be as efficient or reliable as Lodash's implementation or structuredClone()
.