var arr = [];
for (var i = 0; i < 1000; i++) {
arr[i] = i;
}
function someFn(i) {
return i * 3 * 8;
}
arr.forEach(function (item){
someFn(3);
})
for (var i = 0, len = arr.length; i < len; i++) {
someFn(3);
}
arr.forEach(function (item){
someFn(item);
})
for (var i = 0, len = arr.length; i < len; i++) {
someFn(arr[i]);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach_static | |
for_static | |
foreach_index | |
for_index |
Test name | Executions per second |
---|---|
foreach_static | 121221.0 Ops/sec |
for_static | 1188782.6 Ops/sec |
foreach_index | 120196.6 Ops/sec |
for_index | 612025.4 Ops/sec |
I'd be happy to help explain the provided benchmark.
Benchmark Overview
The benchmark measures the performance difference between three approaches to iterate over an array:
forEach
with a callback function that always calls someFn(3)
.for
loop with an index variable.forEach
with a callback function that passes each element of the array to someFn
.Options Compared
The three options compared are:
foreach_static
: Iterating over the array using forEach
with a static callback function that always calls someFn(3)
.for_static
: Using a traditional for
loop with an index variable and calling someFn(3)
in each iteration.foreach_index
: Iterating over the array using forEach
with a dynamic callback function that passes each element to someFn
.foreach_static
, but with more flexibility in the callback function.Library Used
In this benchmark, no external libraries are used. The code only relies on built-in JavaScript features.
Special JS Feature or Syntax
There is no special JavaScript feature or syntax explicitly mentioned in the benchmark. However, forEach
and traditional for
loops are both supported by modern JavaScript engines, making them a good choice for this comparison.
Other Considerations
When writing performance-critical code, it's essential to consider the following factors:
Alternatives
Other alternatives for iterating over arrays include:
map()
: Returns a new array with the results of applying a given function to each element in the original array.filter()
: Returns a new array with elements that pass a test implemented by a provided function.every()
, some()
, and reduce()
can also be used, but they may incur additional overhead due to their more complex logic.In conclusion, this benchmark helps illustrate the trade-offs between using forEach
or traditional for
loops for array iteration. By understanding these options and considering factors like cache locality, branch prediction, and register usage, developers can optimize their code for better performance.