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);
myCopy = {MyObject};
myCopy = Object.assign({}, MyObject);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON.stringify | |
structuredClone | |
spread | |
Object.assign |
Test name | Executions per second |
---|---|
JSON.stringify | 1029025.8 Ops/sec |
structuredClone | 429366.1 Ops/sec |
spread | 9179293.0 Ops/sec |
Object.assign | 7927801.0 Ops/sec |
Let's dive into the benchmark and explain what's being tested.
The benchmark is designed to compare four different methods for creating a deep copy of an object: JSON.stringify
, structuredClone
, spread operator (...
), and Object.assign()
. The goal is to determine which method is the fastest and most efficient.
Here are the pros and cons of each approach:
...
):The benchmark creates an object MyObject
with nested properties and then uses each of the four methods to create a copy of it. The resulting objects are compared to ensure they are identical.
The test cases in the provided JSON represent individual runs of the benchmark, where each run corresponds to one of the four methods being tested.
Now, let's look at some specific notes on the libraries and features used in this benchmark:
structuredClone
is a relatively new function introduced in Chrome 80, designed specifically for creating deep copies. It's still an experimental flag (-XExperimentalJSHostedRuntime) but gaining popularity.If you're interested in exploring alternative methods for creating deep copies, some other options include:
cloneDeep()
functionKeep in mind that the performance differences between these methods may vary depending on specific use cases and requirements.