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 (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 | 1079.4 Ops/sec |
for | 11775325.0 Ops/sec |
map | 1026.5 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, the options compared, their pros and cons, and other considerations.
Benchmark Overview
The benchmark measures the performance of three different approaches to iterate over an array: forEach
, for
loop, and map
. The test case uses a simple JavaScript function someFn
that takes an integer as input and returns the result multiplied by 3 and 8. The input array is created with 10,000 elements using a for loop.
Options Compared
forEach
method, which calls the provided callback function on each element.for
loop to iterate over the array, accessing each element by its index.someFn
function to each element of the array using the map
method.Pros and Cons
forEach
.Library Usage
The someFn
function is not part of any library; it's a custom function defined in the benchmark script. The map
method uses the Array.prototype.map() function from the ECMAScript standard, which is built-in to modern JavaScript engines.
Special JS Feature or Syntax
There are no special features or syntax used in this benchmark that would require additional explanation.
Other Considerations
forEach
and map
, as they allow direct access to array elements.forEach
and map
may incur overhead due to callback function creation and iteration, while traditional for loops tend to have less overhead.Alternatives
Other approaches to iterate over arrays include:
each
: A functional programming alternative to forEach
.map
and forEach
: Functional programming libraries that provide more concise and expressive iteration methods.Keep in mind that the choice of iteration method depends on the specific use case, performance requirements, and personal preference.