var array = new Array(100);
array.forEach(function(item, index) {
return item;
});
array.map(function(item) {
return item;
});
for (const item of array) {
item;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
arr map | |
for of |
Test name | Executions per second |
---|---|
foreach | 4316745.0 Ops/sec |
arr map | 2751032.2 Ops/sec |
for of | 3600731.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark measures the performance of three different approaches to iterate over an array: forEach
, map
, and for-of
. The goal is to determine which approach is the fastest for a given use case.
Library Usage
In the benchmark, the array
object is used, which is a built-in JavaScript object. No external libraries are required or used in this benchmark.
Special JS Feature/Syntax
The benchmark uses the new for...of
loop syntax introduced in ECMAScript 2015 (ES6). This syntax allows you to iterate over an array without the need for explicit indexing or manual iteration.
Options Compared
Here's a summary of what's being compared:
forEach
: Uses the traditional forEach()
method, which takes two arguments: a callback function and an optional context object.map
: Uses the map()
method, which also takes a callback function as its first argument. However, it returns a new array with the results of applying the callback to each element in the original array.for-of
: Uses the new for...of
loop syntax, which allows you to iterate over an array without using indexing or manual iteration.Pros and Cons
Here's a brief pros and cons summary for each approach:
forEach
:item
value twice (once in the callback and once as the loop variable).map
:forEach
because it creates a new array and copies elements over.for-of
:Benchmark Results
The latest benchmark results show that:
foreach
: 4316745 executions per secondfor of
: 3600731 executions per secondarr map
: 2751032.25 executions per secondBased on these results, it appears that the for-of
approach is currently the fastest for this benchmark.
Alternatives
If you need to compare other iteration methods or want more control over your iterations, some alternatives include:
array[index]
) to access elements and update indices.Keep in mind that these alternatives might not be as performant or widely supported as the forEach
, map
, and for-of
methods.