var strs = Array.from(new Array(10000)).map(() => 'String concat. ')
var result = []
result = strs.map((a) => a)
strs.forEach(i => {
result.push(strs[i])
})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
map | |
foreach push |
Test name | Executions per second |
---|---|
map | 25676.9 Ops/sec |
foreach push | 209.0 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition:
The benchmark is defined as a comparison between two approaches:
Array.prototype.map()
to create a new array with transformed values.forEach
loop to iterate over the array and push each value to a result array.Options Compared:
map()
: A method that creates a new array by applying a provided function to each element of an existing array. It returns a new array with the transformed values.forEach
: A method that calls a provided function once for each element in an array, without returning any value.Pros and Cons:
map()
:forEach
:Library Used:
None explicitly mentioned in this benchmark. However, Array.prototype.map()
and forEach
are built-in methods of the JavaScript array object.
Special JS Feature/Syntax:
None mentioned in this specific benchmark.
Now, let's analyze the test results:
The latest benchmark result shows that Chrome 115 on Linux Desktop achieves:
map()
: Executions per second (EPS) of approximately 24,817.99609375.forEach push
: EPS of approximately 690.2704467773438.This suggests that using map()
is significantly faster than using the forEach
loop with push
in this specific benchmark.
Other Alternatives:
Other approaches to achieve the same result could include:
reduce()
method, which can be more efficient for large datasets.map()
and forEach
.It's worth noting that the performance difference between these approaches may vary depending on the specific use case, data size, and JavaScript engine being used.