<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/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 = 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 | 1768567.9 Ops/sec |
Json clone | 1529599.8 Ops/sec |
structuredClone | 715780.2 Ops/sec |
Let's dive into the explanation.
Overview
The provided JSON represents a benchmark test on MeasureThat.net, where three different approaches are compared to clone a JavaScript object: Lodash cloneDeep
, JSON's parse
and stringify
methods, and the structuredClone
function. The test creates a deep copy of an object using each approach and measures their performance.
Options Compared
The options being compared are:
cloneDeep
: A library function that creates a deep copy of an object.parse
and stringify
methods: Built-in JavaScript methods used to parse and convert JSON strings, respectively.structuredClone
function: A new function introduced in ECMAScript 2020, which creates a shallow copy of an object.Pros and Cons
Here are some pros and cons for each approach:
cloneDeep
:parse
and stringify
methods:structuredClone
function:cloneDeep
.Library: Lodash
Lodash is a popular JavaScript utility library that provides various functions for tasks like cloning, mapping, filtering, and more. In this benchmark, Lodash's cloneDeep
function is used to create a deep copy of the input object.
Special JS Feature/Syntax
None mentioned in the provided JSON. However, it's worth noting that some newer JavaScript features, such as Spread Operator
(e.g., {...obj}
) or Object.assign()
methods, might be used in certain cloning scenarios.
Other Alternatives
If you need to clone objects frequently, other alternatives to Lodash cloneDeep
include:
: Creates a deep copy of an object using JSON's
parseand
stringify` methods (as shown in the benchmark).Keep in mind that each approach has its trade-offs, and the best choice depends on your specific use case and performance requirements.