var obj = {a: "hello", c: "test", po: 33, arr: [1, 2, 3, 4], anotherObj: {a: 33, str: "whazzup"}};
const obj1 = JSON.parse(JSON.stringify(obj));
const obj2 = structuredClone(obj);
const obj3 = { obj };
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON stringify and parse | |
structuredClone | |
Destructuring and Restructuring |
Test name | Executions per second |
---|---|
JSON stringify and parse | 1155466.2 Ops/sec |
structuredClone | 692880.2 Ops/sec |
Destructuring and Restructuring | 15998959.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Definition and Preparation Code
The provided JSON represents a benchmark named "Deep clone performance comparison". The script preparation code is:
var obj = {a: "hello", c: "test", po: 33, arr: [1, 2, 3, 4], anotherObj: {a: 33, str: "whazzup"}};
This code creates an object obj
with various properties and values. The object contains a nested object anotherObj
, which is not cloned in the benchmark.
The purpose of this benchmark is to measure the performance of different methods for creating a deep clone of the obj
object.
Options Compared
Three options are compared:
JSON.stringify()
function to convert the object into a string, and then parses it back into an object using JSON.parse()
.{ ...obj }
) to create a new object by copying the properties from obj
.Pros and Cons
Here's a brief overview of each option:
structuredClone
.Other Considerations
When choosing a method for creating deep clones, consider the size of the object, the complexity of its nested structures, and the performance requirements of your application. For small to medium-sized objects, the spread operator might be sufficient. However, for larger or more complex objects, structuredClone()
might be a better choice.
Library Used
The structuredClone()
method is not a built-in function in JavaScript until ECMAScript 2022 (JavaScript version 12). However, it's implemented in some browsers and Node.js environments, starting from version 14.0.0.
Special JS Feature or Syntax
None of the options mentioned require special JavaScript features or syntax beyond what's commonly used in modern web development.
Now that we've explored the benchmark, let's take a look at the results:
The latest benchmark result shows that the "Destructuring and Restructuring" option (using the spread operator) outperforms the other two methods. The "structuredClone()" method is not supported by older browsers or Node.js environments, but it's a modern way of creating deep clones.
If you're interested in exploring alternative approaches, consider using libraries like Lodash, which provides a cloneDeep()
function for creating deep copies of objects. Alternatively, you can use other methods, such as the JSON.parse(JSON.stringify(obj))
approach or even custom functions for cloning specific types of data structures.