function createBigObject(depth) {
const obj = {};
for (let i = 0; i < 5000; i++) {
obj[i + Math.floor(Math.random() * 10000)] = {
[Math.random() * 10000]: Math.random() * 10000,
};
}
return obj;
}
var bigObj = createBigObject()
var clone;
clone = JSON.parse(JSON.stringify(bigObj))
clone = structuredClone(bigObj)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON | |
structuredClone |
Test name | Executions per second |
---|---|
JSON | 408.6 Ops/sec |
structuredClone | 454.1 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and considered.
Benchmark Overview
The benchmark is designed to compare the performance of two approaches: JSON.parse(JSON.stringify())
and structuredClone()
on a large object cloning. The benchmark aims to determine which approach is faster and more efficient.
Test Cases
There are two test cases:
JSON.parse(JSON.stringify())
. This method creates a deep copy of the original object by recursively traversing its properties.structuredClone()
function, which is introduced in ECMAScript 2020 as a new way to create a shallow or deep clone of an object.Comparison
The benchmark compares the performance of these two approaches on a large object cloning:
const bigObj = createBigObject();
var clone;
clone = JSON.parse(JSON.stringify(bigObj)); // Test Case: JSON
vs
structuredClone(bigObj); // Test Case: structuredClone
Options Compared
The benchmark compares the following options:
JSON.parse(JSON.stringify())
creates a deep copy of the original object, which can be slower and more memory-intensive.structuredClone()
creates a shallow clone of the original object, which is faster but may not preserve all properties or values.Pros and Cons
Library and Purpose
The structuredClone()
function is part of the ECMAScript specification and is designed to provide a more efficient way of cloning objects. Its primary purpose is to avoid the overhead of recursive traversal for shallow copies, while still preserving most properties and values.
Special JS Feature or Syntax
structuredClone()
is a relatively new feature introduced in ECMAScript 2020, so it's not surprising that MeasureThat.net includes it as an option. This highlights the importance of keeping up-to-date with the latest JavaScript features and best practices.
Other Alternatives
If you need to clone objects frequently, you might want to consider other options:
cloneDeep()
: A popular utility library function that creates a deep copy of an object.createCopy()
: Another utility library function that creates a shallow or deep copy of an object.Keep in mind that these alternatives might not be as optimized or efficient as the structuredClone()
method, but they can provide a convenient solution when working with JavaScript objects.