<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var o = {
a: {
b: 1,
c: 2,
d: 3,
j: {
k: [1,2,3],
l: [4,5,6]
},
},
e: [1,2,3,4,5,6],
f: 1,
g: {
h: 1,
}
}
const a = _.cloneDeep(o)
const a = JSON.parse(JSON.stringify(o))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
JSON PARSE JSON STRINGIFY |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 127346.7 Ops/sec |
JSON PARSE JSON STRINGIFY | 143338.4 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
What is being tested?
The provided benchmark definition and test cases measure the performance of two different approaches to deep cloning an object in JavaScript:
cloneDeep
: This function creates a deep copy of an object, which means it recursively clones all nested objects and arrays.JSON.parse()
and JSON.stringify()
methods to clone an object.Options compared
The two options are:
cloneDeep
: A third-party library function that provides a efficient way to deep clone objects.Pros and cons of each approach
cloneDeep
:Library: Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for tasks such as array manipulation, object transformation, and more. In this case, the cloneDeep
function is used to create deep copies of objects.
Special JS feature/syntax
None mentioned in the provided code snippet.
Benchmark result analysis
The latest benchmark result shows that:
cloneDeep
: 127346.71875 executions per secondThis suggests that, for this specific test case, the JSON parsing and stringifying approach is slightly faster than using Lodash's cloneDeep
function.
Other alternatives
If you're interested in exploring other options, here are a few:
Object.assign()
: This method can be used to create a shallow copy of an object.Array.prototype.slice()
and Array.prototype.concat()
: These methods can be used to clone arrays.lodash-es
, immer
, or deepcopy
.Keep in mind that the best approach depends on your specific use case and requirements.