<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>
var arr = [
{
"id": 52
},
{
"id": 76
},
{
"id": 13
},
{
"id": 96
},
{
"id": 27
},
{
"id": 8
},
{
"id": 23
},
{
"id": 63
},
{
"id": 25
}
]
arr.map(elem => ({
elem,
className: 'pizza'
}))
_.cloneDeep(arr).map(elem => {
elem.className = 'pizza';
return elem;
})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Native | |
Lodash.js cloneDeep |
Test name | Executions per second |
---|---|
Native | 477461.3 Ops/sec |
Lodash.js cloneDeep | 192071.4 Ops/sec |
Let's break down the benchmark and analyze what's being tested.
Benchmark Overview
The benchmark compares two approaches to create a new array with modified elements: using native JavaScript features (map
function) versus using the cloneDeep
function from the Lodash library. The goal is to measure which approach is faster for creating this specific type of dataset.
Native Approach
In the Native approach, the map
function is used to create a new array with modified elements:
arr.map(elem => ({ ...elem, className: 'pizza' }))
This code uses the spread operator (...
) to create a shallow copy of each element in the original array, and then adds a className
property to each resulting object.
Lodash.js CloneDeep Approach
In the Lodash.js CloneDeep approach, the cloneDeep
function from the Lodash library is used to create a deep copy of the original array:
_.cloneDeep(arr).map(elem => ({ elem.className = 'pizza'; return elem; }))
This code uses cloneDeep
to create a deep copy of the original array, and then applies the same transformation as in the Native approach.
Options Compared
The two approaches are compared in terms of their performance, measured by the number of executions per second. The goal is to determine which approach is faster for creating this specific type of dataset.
Pros and Cons
Library: Lodash
The cloneDeep
function from the Lodash library is used to create a deep copy of the original array. The purpose of this function is to recursively clone all nested properties and arrays, ensuring that the cloned object has the same structure and contents as the original.
Special JS Feature/Syntax
No special JavaScript features or syntax are used in either approach. However, it's worth noting that the Native approach requires modern JavaScript features like arrow functions, spread operator, and template literals (\r\n
).
Alternatives
Other alternatives to create a deep copy of an array include:
JSON.parse(JSON.stringify(arr))
methodKeep in mind that these alternatives may have their own trade-offs and performance characteristics, which may not be identical to the Native or Lodash.js CloneDeep approaches.