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 = JSON.parse(JSON.stringify(MyObject));
myCopy = structuredClone(MyObject);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Json Clone | |
structuredClone |
Test name | Executions per second |
---|---|
Json Clone | 595856.1 Ops/sec |
structuredClone | 290476.2 Ops/sec |
Let's break down the provided JSON benchmark definition and test cases.
Benchmark Definition:
The benchmark measures the performance of two approaches for creating a deep copy of an object:
JSON.parse(JSON.stringify(MyObject))
structuredClone(MyObject)
What is being tested?
The benchmark tests the execution time of these two approaches on a specific JavaScript object (MyObject
). The object contains nested properties, including another object with a string that describes its purpose.
Options compared:
Two options are compared:
JSON.parse(JSON.stringify(MyObject))
: This approach uses the JSON.parse()
method to parse a JSON representation of the object and then creates a new object from it.structuredClone(MyObject)
: This is a newer approach introduced in ECMAScript 2020, which creates a deep clone of an object without serializing it to a string.Pros and Cons:
JSON.parse(JSON.stringify(MyObject))
:structuredClone()
due to the extra parsing step.structuredClone(MyObject)
:JSON.parse(JSON.stringify(MyObject))
.Library:
The benchmark uses the structuredClone
function, which is a built-in JavaScript function introduced in ECMAScript 2020. Its purpose is to create a deep clone of an object without serializing it to a string.
Special JS feature or syntax:
None mentioned in the provided JSON.
Other alternatives:
If you need to support older browsers that don't have structuredClone()
support, you can consider using:
JSON.parse(JSON.stringify(MyObject))
:structuredClone()
.In summary, structuredClone()
is a newer, faster approach for creating a deep clone of an object, while JSON.parse(JSON.stringify(MyObject))
is a widely supported, albeit slower alternative. The choice between these approaches depends on your specific requirements, browser support, and performance considerations.