<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>
var a = {name: 'a',secondName: 'b', home: {city:'San Diego', zip:'92122',phone:{code:484, number:99999999}}}
let b = _.cloneDeep(a)
let b = JSON.parse(JSON.stringify(a))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash | |
Native JS |
Test name | Executions per second |
---|---|
Lodash | 407755.0 Ops/sec |
Native JS | 266364.7 Ops/sec |
Let's break down the provided benchmark and its test cases to understand what's being tested.
Benchmark Definition: The benchmark is created on MeasureThat.net, which allows users to create and run JavaScript microbenchmarks. The benchmark definition consists of two parts:
a
with nested properties, including another object home
. This object will be used as input for the benchmark.Individual Test Cases: The benchmark consists of two test cases:
_.cloneDeep()
function from the Lodash library to clone a deep copy of the object a
. This test case is used to measure the performance of using the Lodash library for cloning.JSON.parse(JSON.stringify(a))
method to create a deep copy of the object a
. This test case is used to measure the performance of using native JavaScript for cloning.Pros and Cons:
Library and Purpose:
The lodash
library is a popular JavaScript utility library that provides various functions for tasks such as:
* Iteration (_.forEach()
, _reduce()
)
* String manipulation (_.trim()
, _upperCase()
)
+ Object manipulation (_.cloneDeep()
, _map()
)
In this benchmark, Lodash is used to provide a convenient way to clone objects, including nested properties.
Special JS Feature/Syntax: There are no special JavaScript features or syntax being tested in these benchmark cases. Both test cases use standard JavaScript constructs for cloning objects.
Other Alternatives: For deep copying objects, you can also consider using the following alternatives:
Array.prototype.slice.call()
: This method creates a shallow copy of an array.Object.assign()
: This method copies properties from one object to another.Immutable.js
(which is now deprecated) or other alternatives like fast-json-stamp
.Keep in mind that these alternatives may have different performance characteristics and might not be as efficient as the Lodash method.