const myObj1 = {};
const numLoops = 1000000;
for (let i = 0; i < numLoops; i += 1){
const myObj2 = JSON.parse(JSON.stringify(myObj1));
}
const myObj1 = {};
const numLoops = 1000000;
for (let i = 0; i < numLoops; i += 1){
const myObj2 = structuredClone(myObj1);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON.parse(JSON.stringify( | |
structuredClone( |
Test name | Executions per second |
---|---|
JSON.parse(JSON.stringify( | 3.0 Ops/sec |
structuredClone( | 0.7 Ops/sec |
Let's dive into the benchmark and explain what's being tested.
The provided JSON represents a JavaScript microbenchmark test case on MeasureThat.net. The test is designed to compare the performance of two different methods for serializing and deserializing objects in JavaScript: JSON.parse(JSON.stringify())
and structuredClone()
.
Options Being Compared:
JSON.stringify()
function to serialize an object, which converts it into a string representation. Then, it uses JSON.parse()
to deserialize the string back into an object.Pros and Cons:
Library Usage:
None of the provided test cases uses a library. Both methods are built-in to JavaScript and rely on the JSON
object.
Special JS Feature/Syntax:
Neither test case uses any special JavaScript features or syntax. The focus is solely on comparing the performance of the two serialization/deserialization methods.
Other Considerations:
When choosing between these two methods, consider the following:
JSON.parse(JSON.stringify())
might be sufficient.structuredClone()
.JSON.parse(JSON.stringify())
can lead to performance issues for large objects.Alternatives:
Other alternatives for serializing and deserializing JavaScript objects include:
cloneDeep()
: A popular utility library that provides a deep-clone function.: Another approach that uses the
slice()method to create a shallow copy of an array or object, followed by
JSON.stringify()` for serialization.Keep in mind that each alternative has its own trade-offs and may not offer the same level of performance or accuracy as structuredClone()
if you're working with complex data structures.