var arr = [];
for (var i = 0; i < 100000; 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]);
}
arr.map(item => someFn(item))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
forEach | |
fori | |
map |
Test name | Executions per second |
---|---|
forEach | 144.4 Ops/sec |
fori | 86.3 Ops/sec |
map | 132.0 Ops/sec |
What is being tested?
MeasureThat.net is testing the performance of three different ways to iterate over an array in JavaScript: forEach
, for
loop, and map
.
The script preparation code creates an empty array arr
and populates it with 100,000 elements using a for loop. It also defines a function someFn(i)
that takes an integer i
as input and returns the result of multiplying i
by 3 and 8.
Options compared:
The three options are:
forEach
: Iterates over the array using the forEach
method, which calls the provided callback function for each element in the array.for
loop: Iterates over the array using a traditional for loop, which increments a counter variable to access each element in the array.map
: Applies the someFn
function to each element in the array and returns an array of results.Pros and Cons of each approach:
forEach
:for
loop:forEach
or map
for large datasets, gives more control over iteration logic.map
:Library and purpose:
The forEach
function is a built-in method in JavaScript, provided by the ECMAScript standard. It allows iterating over an array using a callback function.
Special JS feature or syntax:
None mentioned in this benchmark definition.
Other considerations:
for
loop may be less common today due to the popularity of forEach
and map
, but it can still provide better performance for large datasets.map
can simplify code when working with arrays and functions that take an input, but it creates a new array with the results, which may have memory implications.Alternatives:
If you prefer not to use forEach
or map
, you can also iterate over the array using traditional loops, such as:
while
loop with array bounds checkingfor...in
loop with array iterationAlternatively, you can use more modern alternatives like reduce()
for array reduction, every()
and some()
for array filtering and testing.
Keep in mind that the best approach depends on your specific use case, performance requirements, and coding style.