var MyObject = {
description: 'Creates a deep copy of source, which should be an object or an array.',
myNumber: 10,
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;
MyObject.myNumber++;
myCopy = JSON.parse(JSON.stringify(MyObject));
MyObject.myNumber++;
myCopy = structuredClone(MyObject);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON.stringify | |
structuredClone |
Test name | Executions per second |
---|---|
JSON.stringify | 510404.5 Ops/sec |
structuredClone | 261317.2 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Overview
The benchmark compares two approaches to create a copy of an object: JSON.stringify
and structuredClone
. The test case uses a sample object, MyObject
, which contains nested properties, including a jayson
property that references another string. The goal is to determine which approach is faster and more efficient.
Options Compared
The two options being compared are:
Pros and Cons of each approach:
JSON.stringify
structuredClone
for large objects due to the overhead of serializing and parsing JSON strings.JSON.parse()
on a string that was previously serialized).structuredClone
JSON.stringify
.Library/Functionality Used
In this benchmark, structuredClone
is used to create a deep copy of the MyObject
. structuredClone
is a relatively new function introduced in ECMAScript 2020 (ES2020) as part of the "Object Spread" syntax. It's designed to create a new object with the same properties as an existing one, without serializing or deserializing data.
Special JS Feature/Syntax
There are no special JavaScript features or syntaxes being used in this benchmark. However, it's worth noting that structuredClone
is a relatively new feature that may not be supported in all browsers or environments yet.
Other Alternatives
If you need to create a copy of an object without using structuredClone
, other alternatives include:
cloneDeep()
function: A popular utility library that provides a deep cloning function for objects.Keep in mind that each alternative has its own trade-offs and may not be as efficient or reliable as structuredClone
.