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 (var i = 0, len = arr.length; i < len; i++) {
someFn(arr[i]);
}
for (var i = arr.length - 1; i >= 0; i--) {
someFn(arr[i]);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for norml | |
reverse for |
Test name | Executions per second |
---|---|
foreach | 9798.8 Ops/sec |
for norml | 5251.0 Ops/sec |
reverse for | 5176.8 Ops/sec |
Let's break down the provided benchmark and explain what is being tested, compared, and the pros and cons of each approach.
Benchmark Definition
The benchmark definition provides a JavaScript script that generates an array of 1000 elements and defines a function someFn
that multiplies its input by 3 and 8. The benchmark has two parts:
arr
and populates it with numbers from 0 to 999 using a for
loop.Individual Test Cases
The benchmark has three test cases:
arr.forEach(function (item){someFn(item);})
for (var i = 0, len = arr.length; i < len; i++) {someFn(arr[i]);}
for (var i = arr.length - 1; i >= 0; i--) {someFn(arr[i]);}
Comparison of Approaches
The three test cases compare the performance of different iteration methods:
forEach
method, which is an iterator-based approach that calls the callback function once for each element in the array.for
loop with an index variable i
.for
loop with a reverse iteration order ( starting from the end of the array).Pros and Cons
Here's a brief summary of the pros and cons of each approach:
for
loops with reverse iteration.Library and Special JS Features
There are no libraries used in this benchmark. However, it's worth noting that the forEach
method is a built-in JavaScript feature introduced in ECMAScript 2015 (ES6).
Other Alternatives
Other alternatives for iterating over arrays include:
It's worth noting that the performance differences between these approaches may vary depending on the specific use case and array size.