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.stringify(MyObject));
myCopy = structuredClone(MyObject);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON.stringify | |
structuredClone |
Test name | Executions per second |
---|---|
JSON.stringify | 1049695.6 Ops/sec |
structuredClone | 714738.4 Ops/sec |
This benchmark evaluates and compares the performance of two methods for creating deep copies of JavaScript objects: JSON.stringify
combined with structuredClone
, and structuredClone
directly. Let's break down the components and considerations of this benchmark.
Benchmark Method: JSON.stringify
with structuredClone
myCopy = structuredClone(JSON.stringify(MyObject));
MyObject
into a JSON string using JSON.stringify
and then uses structuredClone
to create a deep copy of that string.Benchmark Method: structuredClone
Directly
myCopy = structuredClone(MyObject);
structuredClone
is called directly on the MyObject
, taking advantage of its built-in functionality for deep copying.undefined
, symbols, etc.).Date
and Map
.structuredClone
is generally good, but it's always wise to check compatibility for older browsers.JSON.stringify
is more widely supported but also less efficient for deep cloning.lodash.cloneDeep
are commonly used in practice as they provide additional features and handle edge cases that both methods may not address.Lodash's cloneDeep: A popular utility library that provides a cloneDeep
method capable of deeply cloning any JavaScript object efficiently, handling many edge cases and data types.
Manual Deep Copying: Implementing a custom solution by recursively copying object properties can be an alternative but often leads to complications, especially with circular references and complex types.
This benchmark clearly demonstrates the performance differences between JSON.stringify
and structuredClone
. For the specific task of deep cloning, structuredClone
is the more effective and efficient choice, while JSON.stringify
, although useful in other contexts, introduces unnecessary overhead when used solely for deep copying. Software engineers, regardless of their familiarity with JavaScript, are encouraged to consider the appropriate use cases, performance implications, and limitations of each method when deciding which to utilize.