var arr = [];
for (var i = 0; i < 1000000; i++) {
arr[i] = i;
}
function someFn(i) {
return i * 3 * 8;
}
arr.forEach(someFn)
for (var i = 0, len = arr.length; i < len; i++) {
someFn(arr[i]);
}
arr.map(someFn)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for | |
map |
Test name | Executions per second |
---|---|
foreach | 68.7 Ops/sec |
for | 4.7 Ops/sec |
map | 53.4 Ops/sec |
Let's break down the provided benchmarking test cases and explain what is being tested, along with their pros and cons.
Benchmark Description
The benchmark compares the performance of three different approaches for iterating over an array: forEach
, for
loop, and map
.
Script Preparation Code
The script preparation code creates a large array (arr
) with 1 million elements, each initialized to its index value. It also defines a simple function someFn(i)
that multiplies the input by 3 and 8.
Html Preparation Code
There is no HTML preparation code provided, which means the benchmarking test cases are focused solely on JavaScript performance.
Individual Test Cases
Each test case corresponds to one of the three iteration approaches:
foreach
: This test case uses the forEach
method to iterate over the array and apply the someFn(i)
function to each element.for
loop: This test case uses a traditional for
loop to iterate over the array, calling someFn(arr[i])
for each element.map
: This test case uses the map()
method to create a new array with the results of applying someFn(i)
to each element in the original array.Pros and Cons of Each Approach
Here's a brief summary:
forEach
:for
loop:forEach
.map()
:Library and Special JS Features
None of the test cases explicitly use any libraries or special JavaScript features. The forEach
method is a built-in array method, while for
loops and map()
are also standard constructs.
However, it's worth noting that some modern browsers may optimize forEach
by using SIMD (Single Instruction, Multiple Data) instructions, which can provide performance benefits. This optimization is not present in the provided benchmarking test cases.
Other Alternatives
Alternative iteration approaches could include:
for
loop with indexing (for (var i = 0; i < arr.length; i++)
)reduce()
to iterate over the arrayKeep in mind that these alternatives may have different performance characteristics and trade-offs.
Overall, this benchmark helps evaluate the performance of three common iteration approaches in JavaScript, providing insights into their strengths and weaknesses.