<script src=''></script>
var arr = [];
for (var i = 0; i < 10000; i++) {
arr[i] = i;
}
function someFn(i) {
return i * 3 * 8;
}
arr.forEach(function (item){
someFn(item);
})
for (var i = 0, len = arr.length; i < len; i++) {
someFn(arr[i]);
}
arr.map(item => someFn(item))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for | |
map |
Test name | Executions per second |
---|---|
foreach | 855.0 Ops/sec |
for | 505.7 Ops/sec |
map | 777.2 Ops/sec |
Let's break down the benchmark and its test cases.
Benchmark Overview
The benchmark measures the performance of three approaches to iterate over an array: forEach
, for
loop, and map
. The test case is designed to compare the execution speed of these approaches on a large array of 10,000 elements.
Test Case 1: foreach
In this test case, the forEach
method is used to iterate over the array. The callback function someFn(i)
is executed for each element in the array. The purpose of this test is to measure the overhead of using a functional programming approach to iterate over an array.
Pros and Cons:
Test Case 2: for
loop
In this test case, a traditional for
loop is used to iterate over the array. The loop variable i
is incremented manually for each iteration.
Pros and Cons:
Test Case 3: map
In this test case, the map
method is used to create a new array by applying the someFn(i)
function to each element in the original array.
Pros and Cons:
Library Used:
In all three test cases, the someFn(i)
function is used. This function takes an integer i
as input and returns a calculated value (i * 3 * 8
). The purpose of this function is to simulate some compute-intensive operation.
Special JS Feature/Syntax:
None of the test cases use any special JavaScript features or syntax that would impact their performance in a non-standard way.
Alternative Approaches:
Other alternatives for iterating over an array include:
while
loopforEach
with a custom callback function (not as efficient as using map
)reduce()
instead of map
Note that the choice of iteration approach depends on the specific use case and performance requirements.