let arr = Array(10000);
arr.fill({name: 'ddd', age: 123});
const newArr1 = []
const newArr2 = []
arr.forEach((v) => {
newArr1.push(v.name)
newArr2.push(v.age)
})
let arr = Array(10000);
arr.fill({name: 'ddd', age: 123});
const newArr2 = []
const newArr1 = arr.map((v) => {
newArr2.push(v.age)
return v.name
})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
map |
Test name | Executions per second |
---|---|
foreach | 5253.7 Ops/sec |
map | 4218.8 Ops/sec |
Let's break down the provided JSON data and explain what's being tested, compared, and some of the considerations involved.
Benchmark Definition
The provided benchmark is called "foreach vs map by wayne". It's a simple JavaScript microbenchmark that compares the performance of two approaches:
forEach
loop to iterate over an array and push values into two separate arrays.map()
function to create a new array with transformed values.Script Preparation Code
The script preparation code is empty, which means the benchmarker doesn't need to perform any initialization or setup before running the tests.
Html Preparation Code
Similarly, the HTML preparation code is also empty, indicating that no specific HTML structure needs to be generated for this benchmark.
Individual Test Cases
There are two test cases:
forEach
loop to iterate over an array and push values into two separate arrays (newArr1
and newArr2
). The forEach
callback function has access to the current value of each element in the original array, which is stored in the variable v
.map()
function to create a new array with transformed values. The map()
callback function returns the transformed value for each element in the original array.Test Results
The latest benchmark result shows that the map()
approach outperforms the forEach
approach on this particular benchmark, with 2.25 times more executions per second (9161.1337890625 vs 4062.207275390625).
Comparison Options
Here's a brief summary of the options being compared:
map()
.map()
due to the need to create intermediate arrays.forEach
since it avoids creating intermediate arrays.Library: Lodash (not explicitly used in this benchmark)
While not explicitly mentioned, the use of forEach()
and map()
suggests that the developer is familiar with JavaScript's built-in array methods. If a library like Lodash were to be used in this benchmark, it might introduce additional overhead or alter the results.
Special JS Feature/Syntax
There are no special JavaScript features or syntaxes being tested in this benchmark.
Alternatives
Some alternative approaches that could have been explored in this benchmark include:
filter()
to create a new array with filtered values.reduce()
to accumulate values into an object.Keep in mind that the choice of approach depends on the specific requirements and constraints of the project.