<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js'></script>
const a = {test:{val:[1]}}
const b = _.cloneDeep(a);
b.test.val[0] = 2;
if(a.test.val[0] === b.test.val[0] ){
throw new Error("Shallow Cloned")
}
const a = {test:{val:[1]}}
const b = JSON.parse(JSON.stringify(a))
b.test.val[0] = 2;
if(a.test.val[0] === b.test.val[0] ){
throw new Error("Shallow Cloned")
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash | |
JSON.stringify.parse |
Test name | Executions per second |
---|---|
Lodash | 1297234.8 Ops/sec |
JSON.stringify.parse | 2321556.0 Ops/sec |
Let's break down the provided benchmark JSON and explain what's being tested.
Overview
The website MeasureThat.net allows users to create and run JavaScript microbenchmarks. The provided JSON represents two test cases: Lodash
and JSON.stringify.parse
. These test cases compare the performance of two approaches for creating a deep copy of an object: using Lodash's cloneDeep
function versus using JSON.parse(JSON.stringify(a))
.
Options being compared
The two options being compared are:
cloneDeep
function: This function creates a deep copy of an object by recursively cloning its properties.JSON.parse(JSON.stringify(a))
: This method uses JSON serialization and deserialization to create a deep copy of an object.Pros and Cons
Here are some pros and cons of each approach:
cloneDeep
function:JSON.parse(JSON.stringify(a))
:cloneDeep
.Library and purpose
In the provided benchmark, Lodash is a popular JavaScript library that provides utility functions for tasks like array manipulation, object creation, and more. cloneDeep
is one of these utility functions, designed to create deep copies of objects.
Special JS feature or syntax
There are no special JavaScript features or syntax mentioned in the provided benchmark JSON.
Other alternatives
If you're looking for alternative methods to create a deep copy of an object, here are some options:
cloneDeep
, Object.assign()
can be used to create a shallow copy of an object.: For arrays, you can use
slice()` to create a shallow copy. However, for more complex data structures (e.g., objects), this approach may not work as expected.Keep in mind that creating deep copies of complex objects can be challenging and may require manual implementation or the use of libraries like Lodash.
In summary, the provided benchmark compares the performance of two approaches to create a deep copy of an object: using Lodash's cloneDeep
function versus using JSON.parse(JSON.stringify(a))
. While both methods have their pros and cons, Lodash's cloneDeep
is generally considered more efficient and widely used.