var obj = {
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 str = JSON.stringify(obj);
JSON.parse(str);
structuredClone(obj);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON.parse | |
structuredClone |
Test name | Executions per second |
---|---|
JSON.parse | 409979.9 Ops/sec |
structuredClone | 169861.7 Ops/sec |
Let's break down the benchmark and its results.
Benchmark Overview
The benchmark compares the performance of two JavaScript methods: JSON.parse()
and structuredClone()
. Both methods are used to parse or create a copy of a JSON string.
What is tested?
Options compared
The two options being compared are:
JSON.parse()
: This method parses a JSON string into a JavaScript object.structuredClone()
: This method creates a deep clone of a value, including objects and arrays.Pros and Cons:
JSON.parse()
:JSON.parse()
creates a new object, which may incur additional memory allocation and garbage collection.Library or special JS feature
The benchmark uses structuredClone()
which is a modern JavaScript feature introduced in ECMAScript 2020. It's designed to provide a more efficient and flexible way of cloning values, including objects and arrays.
Other considerations
Alternatives
If you need to clone or parse JSON data in your JavaScript application:
JSON.parse()
for simple cases where performance is not critical, or when support for structuredClone()
is not available.cloneDeep()
or Immutable.js's clone()
for more complex cloning scenarios, which may provide better performance and control.structuredClone()
if your target browser supports it.In summary, the benchmark compares the performance of two methods for parsing or creating a copy of JSON data: JSON.parse()
and structuredClone()
. The choice between these methods depends on the specific requirements of your application, including performance needs, compatibility with different browsers, and memory usage considerations.