var obj = {a: "hello", c: "test", po: 33, arr: [1, 2, 3, 4], anotherObj: {a: 33, str: "whazzup"}};
var obj2 = JSON.parse(JSON.stringify(obj));
var obj2 = Object.assign({}, obj);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON.parse | |
Object.assign |
Test name | Executions per second |
---|---|
JSON.parse | 965243.4 Ops/sec |
Object.assign | 4322022.0 Ops/sec |
Let's dive into the benchmark and explain what's being tested.
Benchmark Purpose
The benchmark is designed to compare two approaches for creating a deep clone of an object in JavaScript:
JSON.parse(JSON.stringify(obj))
Object.assign({}, obj)
Approaches Comparison
Both approaches aim to create a new, independent copy of the original object obj
. However, they differ in their implementation:
JSON.stringify()
function to serialize the object and then parses the resulting string back into an object using JSON.parse()
. The JSON.stringify()
function can create a deep clone of objects that implement the JSONSerializable
interface, which includes many built-in JavaScript types like arrays, dates, numbers, etc....
) to create a shallow copy of an object and then uses Object.assign()
to assign the cloned properties to a new object. While this approach is simple and widely supported, it may not work correctly for nested objects that contain other objects as values.Pros and Cons
Here are some pros and cons of each approach:
JSONSerializable
, can be slower due to string serialization.Library Used
In this benchmark, no specific library is used. However, JSON.stringify()
relies on the JSON serializer in your JavaScript implementation, which might be a built-in part of the browser or a separate module.
Special JS Features or Syntax
None are explicitly mentioned in the provided benchmark definition.
Other Alternatives
Other approaches for creating deep clones of objects include:
Object.assign()
with an object that has the same structure as the original object, but uses different variables to create the clone.Keep in mind that these alternatives might have their own pros and cons, which are not detailed here.