var obj = {
cycle: {
cycle: {
cycle: {
cycle: {
cycle: {
cycle: {
cycle: {
cycle: 1
}
}
}
}
}
}
}
}
JSON.parse(JSON.stringify(obj));
structuredClone(obj);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON | |
structuredClone |
Test name | Executions per second |
---|---|
JSON | 732920.5 Ops/sec |
structuredClone | 405058.5 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Definition
The benchmark defines two different approaches to compare:
JSON.parse(JSON.stringify(obj));
structuredClone(obj);
These two methods are used to serialize and deserialize an object, specifically a complex cyclic graph represented by the JSON string in the "Script Preparation Code".
What is being tested?
In this case, we're testing how efficient each method is at handling cyclic graphs, which can occur when objects reference themselves indirectly.
Options compared
The two methods are:
JSON.parse(JSON.stringify(obj));
: This method uses the JSON Stringify function to convert the object to a string, and then parses it back using JSON.parse() with the same options as before (e.g., null as the replacer function). The replacer function is not specified, which means that any circular references will be converted to [Circular]
strings.structuredClone(obj);
: This method uses the structuredClone()
function introduced in ECMAScript 2020, which provides a more efficient and safer way to create deep copies of objects while handling cyclic graphs.Pros and Cons
structuredClone()
function).Library/Feature
The test uses the structuredClone()
function, which is a feature introduced in ECMAScript 2020. This library-like function provides a more efficient and safer way to create deep copies of objects while handling cyclic graphs.
Special JS features or syntax
There are no special JavaScript features or syntax mentioned in this benchmark. The focus is on comparing the performance of two methods for serializing and deserializing an object with a cyclic graph.
Other alternatives
If the structuredClone()
function is not supported by modern browsers, other approaches can be used:
JSON.parse(JSON.stringify(obj))
with a custom replacer function to handle circular references.In summary, the benchmark tests the performance of two methods for serializing and deserializing an object with a cyclic graph: JSON.parse(JSON.stringify(obj));
and structuredClone(obj);
. The latter is considered safer and more efficient, but its implementation requires modern browsers that have implemented this feature.