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.stringify(MyObject);
myCopy = structuredClone(MyObject);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON.stringify | |
structuredClone |
Test name | Executions per second |
---|---|
JSON.stringify | 3020609.8 Ops/sec |
structuredClone | 706589.9 Ops/sec |
The provided benchmark evaluates the performance of two JavaScript methods for creating deep copies of objects: JSON.stringify
and structuredClone
. Each approach serves the purpose of cloning an object, but they differ significantly in how they achieve this, the types of objects they can handle, and their performance.
JSON.stringify:
JSON.parse
to reconstruct the original object.undefined
, and cyclic references.structuredClone:
JSON.stringify
. As of recent updates, structuredClone
is generally available in modern browsers but may not be available in older environments.The benchmark results show the number of executions per second for each method:
While JSON.stringify
demonstrates higher execution rates in this benchmark, the choice between these methods should consider:
JSON.stringify
may be sufficient. However, for more complex cases, structuredClone
is the more robust option despite its slower performance in this specific benchmark.Other alternatives for deep copying objects in JavaScript include:
cloneDeep
Method: A library method that provides a deep copy functionality with full support for various data types. It is well-optimized and can handle cases that JSON.stringify
and even structuredClone
struggle with.In summary, both JSON.stringify
and structuredClone
have their strengths and weaknesses regarding deep copying, and the choice should be guided by the requirements of the specific use case.