var arr = [];
for (var i = 0; i < 999999; i++) {
arr[i] = i;
}
function someFn(i) {
return i * 3 * 8;
}
arr.forEach(function (item){
someFn(item);
})
let len = arr.length;
for (var i = 0; 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 | 141.9 Ops/sec |
for | 121.8 Ops/sec |
map | 34.2 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition
The benchmark measures the performance of three different approaches to iterate over an array:
Array.forEach()
for
loopmap()
In the provided JSON, we have three test cases: foreach
, for
, and map
. Each test case has a corresponding benchmark definition in the format of arr.[iteration method](function (item) { return someFn(item); })
.
Options Compared
The benchmark compares the performance of three different iteration methods:
Array.forEach()
: This method iterates over an array using a callback function, which is executed for each element in the array.for
loop: This approach uses a traditional for
loop to iterate over the array, where the index i
is incremented on each iteration.map()
: This method creates a new array with the results of applying the provided function to each element in the original array.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Array.forEach()
:for
loop:map()
:Libraries Used
None in this specific benchmark. The test code only uses standard JavaScript features and libraries (e.g., Array
).
Special JS Features/Syntax
There are no special JavaScript features or syntaxes used in this benchmark, other than the let
keyword for declaring variables (which is a modern JavaScript feature introduced in ECMAScript 2015).
Other Alternatives
If you're interested in exploring alternative iteration methods, here are some additional approaches:
Array.reduce()
: This method reduces an array to a single value by applying a function to each element.Array.some()
or Array.every()
: These methods test whether at least one (or all) elements in the array pass a provided condition.These alternative iteration methods can be useful in specific scenarios, but might not be as commonly used as forEach
, for
, and map
.
I hope this explanation helps you understand the benchmark and its approaches!