var arr = [];
for (var i = 0; i < 1000; i++) {
arr[i] = i;
}
function someFn(i) {
return i * 3 * 8;
}
arr.forEach(function (item){
someFn(item);
})
for (let i = 0; i < arr.lenght; 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 | 15124.1 Ops/sec |
for | 15546051.0 Ops/sec |
map | 13845.1 Ops/sec |
Let's break down the benchmark and its test cases.
What is being tested?
MeasureThat.net is testing the performance of three different approaches to iterate over an array in JavaScript:
for
loop that iterates over the elements of the array using an index variable.forEach
Loop: The forEach
method, which calls a provided callback function once for each element in the array.map
Method: The map
method, which creates a new array with the results of applying a provided function to each element in the original array.Options compared
The three approaches are being tested as follows:
for
loop with an index variable.forEach
Loop: The forEach
method with a callback function.map
Method: The map
method, which returns a new array with transformed elements.Pros and Cons
Here's a brief overview of the pros and cons of each approach:
forEach
Loopmap
MethodforEach
Loop for large datasets.Library and its purpose
None of the test cases use a specific library. However, it's worth noting that both forEach
and map
methods rely on the Array.prototype.forEach()
and Array.prototype.map()
methods, which are part of the ECMAScript standard.
Special JS feature or syntax
None of the test cases use any special JavaScript features or syntax that would require additional explanation. The only notable feature is the use of arrow functions (=>
) in the map
method, but this is a relatively modern and widely supported feature.
Other alternatives
Some alternative approaches to iterating over an array in JavaScript include:
while
loop instead of a for
loop.for...of
loop (introduced in ECMAScript 2015) for more concise iteration.reduce()
method or other array methods for different types of transformations.However, these alternatives are not being tested by MeasureThat.net.