const arr = [{ name: 'luna', id: 3 },{ name: 'abc', id: 4 }, { name: 'eee', id: 3 }]
const arr = [{ name: 'luna', id: 3 },{ name: 'abc', id: 4 }, { name: 'eee', id: 3 }]
const newArr = arr.map(e=> ({ label: e.name, id: e.id}))
const arr = [{ name: 'luna', id: 3 },{ name: 'abc', id: 4 }, { name: 'eee', id: 3 }]
const newArr = [];
arr.forEach(item => {
newArr.push({ label: item.name, id: item.id })
})
const arr = [{ name: 'luna', id: 3 }, { name: 'abc', id: 4 }, { name: 'eee', id: 3 }];
const arrLength = arr.length;
const newArr = [];
for (let i = 0; i < arrLength; i++) {
newArr.push({ label: arr[i].name, id: arr[i].id });
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
map | |
foreach | |
for |
Test name | Executions per second |
---|---|
map | 5266813.5 Ops/sec |
foreach | 5999242.5 Ops/sec |
for | 6691300.0 Ops/sec |
Let's break down the benchmark test cases and explain what is being tested.
Benchmark Test Cases
The benchmark test cases are comparing three different approaches to process an array of objects:
map()
: This method creates a new array with the results of applying a provided function on every element in this array.forEach()
: This method calls a provided callback function once for each element in an array, without returning any value.for
loop: This is a traditional loop that iterates over the elements of an array.Options being compared
The three approaches are being compared to determine which one is faster and more efficient.
Pros and Cons of each approach:
map()
:forEach()
:for
loop:Library usage
None of the test cases use any external libraries.
Special JS features or syntax
The map()
method uses a modern JavaScript feature called "arrow functions" (=>
), which is a shorthand way to define small, anonymous functions. The forEach()
method does not use any special features, and the for
loop uses traditional variable declarations.
Other alternatives
There are other approaches that could be compared in this benchmark:
reduce()
: This method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.Array.prototype.filter()
: This method creates a new array with all elements that pass the test implemented by the provided function.Array.prototype.forEach()
with a loop or creating a custom iterator.However, these alternatives are not currently being tested in this benchmark.
Overall, this benchmark provides a simple and concise way to compare the performance of different array processing methods in JavaScript.