<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
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);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON parse | |
Native structuredClone |
Test name | Executions per second |
---|---|
JSON parse | 1819903.8 Ops/sec |
Native structuredClone | 678763.6 Ops/sec |
What is being tested?
On the provided JSON, two individual test cases are defined to compare the performance of two approaches: JSON.parse()
and structuredClone()
. The tests aim to create a deep copy of an object (MyObject
) and measure the execution time for each approach.
Options compared
The options being compared are:
JSON.parse(JSON.stringify(MyObject))
: This method uses the JSON.stringify()
function to serialize the object, creates a new string representation of the object, and then parses it back into an object using JSON.parse()
. The resulting object is a shallow copy of the original.structuredClone(MyObject)
: This is a native JavaScript function introduced in ECMAScript 2020 (ES10) that creates a deep clone of an object.Pros and cons
JSON.parse(JSON.stringify())
:structuredClone()
:Library and its purpose
The provided HTML includes a reference to Lodash.js, which is a utility library. In this specific benchmark, Lodash's structuredClone()
function is used as the native implementation for deep cloning objects.
Special JS feature or syntax
structuredClone()
is a special JavaScript feature introduced in ECMAScript 2020 (ES10). It's not widely supported yet and requires modern browsers that have implemented ES10. The benchmark uses this feature to test its performance.
Other alternatives
For non-modern browsers, other libraries like jQuery (1.4.x or later) provide a clone()
method or similar functionality. However, the performance of these alternatives may vary compared to native implementations.
In summary, the provided benchmark tests two approaches for creating deep copies of objects: the widely supported but potentially shallow copy with JSON.parse(JSON.stringify())
, and the modern, accurate copy with structuredClone()
.