var arr = [];
for (var i = 0; i < 10000; i++) {
arr[i] = i;
}
arr.forEach(item => console.log(item))
for (var i = 0, len = arr.length; i < len; i++) {
console.log(arr[i]);
}
arr.map(item => console.log(item))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for | |
map |
Test name | Executions per second |
---|---|
foreach | 9.0 Ops/sec |
for | 8.7 Ops/sec |
map | 8.9 Ops/sec |
Let's dive into the provided benchmark JSON and explain what's being tested.
Benchmark Definition
The benchmark is testing three approaches to iterate over an array:
forEach
method to iterate over the array, which calls a callback function for each element in the array.for
loop with an index variable to iterate over the array elements.map
method to create a new array with transformed values, but since we only log the result to console without returning anything, it's more of a testing iteration rather than actual mapping.Options Compared
The benchmark is comparing three different approaches:
Each approach has its own pros and cons:
Library and Special JS Features
In this benchmark, no libraries are explicitly mentioned. However, the forEach
method is part of the ECMAScript standard, so it doesn't require any additional libraries to work.
No special JavaScript features or syntax are being tested in this benchmark.
Alternative Approaches
Other approaches that could be used for iterating over an array include:
These alternatives have their own pros and cons, and some might perform better or worse than the three tested approaches in this benchmark.
For example:
Overall, the benchmark provides a good starting point for comparing the performance of different iteration approaches in JavaScript.