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 = structuredClone(JSON.parse(JSON.stringify(MyObject)));
myCopy = structuredClone(MyObject);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON.stringify | |
structuredClone |
Test name | Executions per second |
---|---|
JSON.stringify | 493455.4 Ops/sec |
structuredClone | 710679.6 Ops/sec |
The benchmark defined in the provided JSON compares the performance of two methods for creating a deep copy of a JavaScript object: JSON.stringify
combined with JSON.parse
, versus using the structuredClone
method. Below is an explanation of the two approaches being compared, their pros and cons, and other considerations that software engineers might find useful.
JSON.stringify + JSON.parse
myCopy = structuredClone(JSON.parse(JSON.stringify(MyObject)));
JSON.stringify
, and then parses that string back into a JavaScript object using JSON.parse
. This effectively creates a deep copy of the original object.structuredClone
myCopy = structuredClone(MyObject);
structuredClone
is a built-in JavaScript function introduced to create a deep copy of objects, including handling complex types like Date, Map, Set, and others that JSON.stringify
cannot manage directly.JSON.stringify + JSON.parse
Pros:
Cons:
structuredClone
, as it involves two operations (stringification and parsing).structuredClone
Pros:
Cons:
Performance: As seen in the benchmark results, structuredClone
achieved approximately 710,679 executions per second, significantly faster than the JSON.stringify
+ JSON.parse
method, which achieved around 493,455 executions per second. The performance difference can be meaningful for applications that require frequent object copying, such as in Redux state management or when dealing with large data structures.
Use Cases: The choice between these methods should be based on use case requirements. If you need a deep copy of a simple object that contains only serializable properties, the JSON methods might suffice. However, for objects with complex structures, prefer structuredClone
.
Alternatives: Other alternatives for deep copying in JavaScript include:
cloneDeep
: An external library that provides deep cloning functionality with support for many complex types.In conclusion, understanding the strengths and weaknesses of these approaches allows engineers to select the appropriate method for deep cloning objects in JavaScript based on their specific requirements. It is recommended to favor structuredClone
for its versatility and performance advantages in modern JavaScript development, provided that browser compatibility and support are accounted for.