<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 | |
Structured Clone API | |
JSON Parse |
Test name | Executions per second |
---|---|
Lodash | 1224300.2 Ops/sec |
Structured Clone API | 572172.4 Ops/sec |
JSON Parse | 1096192.5 Ops/sec |
What is being tested on the provided JSON?
The benchmark tests three different approaches to create a deep copy of an object in JavaScript:
cloneDeep
function from the Lodash library is used to create a deep copy of the MyObject
.structuredClone
function, which is part of the WebAssembly (WASM) standard, is used to create a deep copy of the MyObject
.JSON.parse(JSON.stringify(MyObject))
method is used to create a deep copy of the MyObject
. This approach serializes the object to a JSON string, then parses it back into an object.Options comparison
The benchmark compares the execution time and performance of these three approaches:
cloneDeep
is specifically designed to create deep copies of objects.JSON.stringify()
, then parses it back into an object using JSON.parse()
.Pros and Cons
Here are some pros and cons for each approach:
Other considerations
cloneDeep
, such as array manipulation functions. However, these are not relevant to this specific benchmark.Library descriptions
Special JS features or syntax
The benchmark uses the structuredClone
function, which is a relatively new feature in JavaScript (introduced in ECMAScript 2021). This function provides an efficient way to create deep copies of objects and is specifically designed for use with WebAssembly.