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;
var obj = {
[Math.random(2000).toString()]: Math.random(2000).toString(),
MyObject,
[Math.random(2000).toString()]: Math.random(2000).toString(),
};
myCopy = JSON.parse(JSON.stringify(obj));
var obj = {
[Math.random(2000).toString()]: Math.random(2000).toString(),
MyObject,
[Math.random(2000).toString()]: Math.random(2000).toString(),
};
myCopy = structuredClone(obj);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON.stringify | |
structuredClone |
Test name | Executions per second |
---|---|
JSON.stringify | 90733.9 Ops/sec |
structuredClone | 82405.9 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares the performance of JSON.stringify()
and structuredClone()
in creating a deep copy of an object. The object has some randomly generated properties, including arrays and a nested object with a string value.
Options Compared
Two options are compared:
JSON.stringify()
: This method converts a JavaScript value to a JSON string, which is then parsed back into a JavaScript object using JSON.parse()
. The resulting object is not a deep copy of the original.structuredClone()
: This is a relatively new function introduced in JavaScript 2020 (ECMAScript 2020) as part of the WebAssembly feature. It creates a deep clone of an object, including arrays and nested objects.Pros and Cons
JSON.stringify()
:
Pros:
Cons:
structuredClone()
due to the additional parsing step.structuredClone()
:
Pros:
JSON.stringify()
.Cons:
Library and Special JS Feature
In this benchmark, no specific library is used. However, note that the use of structuredClone()
relies on a relatively new JavaScript feature.
Test Case Analysis
The two test cases are identical, but they differ in the implementation:
JSON.stringify()
: This test case uses the JSON.stringify()
method to create a copy of the object.structuredClone()
: This test case uses the structuredClone()
function to create a deep clone of the object.Both tests aim to measure the performance difference between these two approaches.
Other Alternatives
If you need an alternative for creating deep copies, consider using:
cloneDeep()
method: A popular library that provides a safe and efficient way to create deep clones._cloneDeep()
function: Another widely used library that offers similar functionality.These alternatives can provide more flexibility and control over the cloning process, but they may introduce additional dependencies or complexity.