var arr = Array(1_000_000);
for (let i = 0; i < 1_000_000; i++) {
arr[i] = { num: Math.random() };
}
var newArr = [];
let l = arr.length;
let i = -1;
while (++i < l) {
newArr.push(arr[i].num);
}
var newArr = [];
var l = arr.length;
for (var i = 0; i < l; i++) {
newArr.push(arr[i].num);
}
var newArr = [];
for (var val of arr) {
newArr.push(val.num);
}
var newArr = arr.map(val => val.num);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
while | |
for | |
for-of | |
.map |
Test name | Executions per second |
---|---|
while | 6.0 Ops/sec |
for | 6.4 Ops/sec |
for-of | 18.4 Ops/sec |
.map | 12.0 Ops/sec |
Let's break down the benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Overview
The benchmark is comparing four different approaches to iterate over an array and extract a specific value:
while
for
for-of
(also known as "foreach").map
The test case creates an array of 1 million elements, each containing a random number between 0 and 100.
Library Used
In the benchmark code, no external library is used. However, some browsers might use their own libraries or optimized versions of these algorithms under the hood.
Special JS Features/Syntax
There are no special JavaScript features or syntaxes being tested in this benchmark. It's a straightforward example of comparing different iteration techniques.
Benchmark Test Cases
Let's analyze each test case:
while
: This loop uses an incrementing index (i
) to iterate over the array, and pushes each value to a new array (newArr
). The pros of this approach are:for
: This loop uses a fixed index (i
) to iterate over the array, and pushes each value to a new array (newArr
). The pros of this approach are:while
.
However, the cons are:while
loop.for-of
(foreach): This loop uses a foreach loop to iterate over the array, and pushes each value to a new array (newArr
). The pros of this approach are:while
and for
..map()
: This method uses a callback function to transform each element in the array, and returns a new array with the transformed values. The pros of this approach are:Other Alternatives
Other alternatives to these four approaches include:
Array.prototype.forEach()
: Similar to for-of
, but without the iteration over the array's length.Array.prototype.reduce()
: Uses a cumulative reduction operation to accumulate values in an array, which can be more efficient than pushing values to a new array.Additional Considerations
When choosing an iteration technique for performance-critical code:
I hope this explanation helps you understand what's being tested in the benchmark!