var array = new Array(10000);
for (let i = 0; i < array.length; i++) {
array[i] = i;
}
let sum = 0;
for (let i = 0; i < array.length; i++) {
sum += array[i];
}
let sum = 0;
for (let item in array) {
sum += item;
}
let sum = 0;
array.forEach(function(item, index) {
sum += item;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
for each | |
forEach |
Test name | Executions per second |
---|---|
for | 650.6 Ops/sec |
for each | 3595.0 Ops/sec |
forEach | 22844.0 Ops/sec |
I'll explain the benchmark and its results in detail.
Benchmark Overview
The benchmark measures the performance of three different ways to sum up the elements of an array:
array.length
as the iteration variable.for...in
loop, which iterates over each property (i.e., element) in the object.Array.prototype.forEach()
function.Benchmark Preparation Code
The preparation code sets up an array with 10,000 elements and initializes its values using a for loop:
var array = new Array(10000);
for (let i = 0; i < array.length; i++) {
array[i] = i;
}
Test Cases
There are three test cases in this benchmark:
for...in
loop to iterate over each element in the array and sum them up.Array.prototype.forEach()
function with a callback function to iterate over each element in the array and sum them up.Library Used
None of these test cases use any external libraries. The forEach
function is part of the ECMAScript standard, while the traditional for loop and for each loop are also standard JavaScript constructs.
Special JS Features or Syntax
There's no special feature or syntax used in this benchmark. All three test cases use standard JavaScript constructs to achieve their goals.
Pros and Cons of Each Approach
Here's a brief analysis of the pros and cons of each approach:
in
operators to iterate over object properties. Cons - less intuitive and error-prone than traditional for loops.Benchmark Results
The latest benchmark results show that the forEach
function consistently outperforms both the traditional for loop and the for each loop, especially on modern browsers like Chrome 104.
Test Name | Executions Per Second |
---|---|
foreach | 22843.99609375 |
for each | 3595.048828125 |
for | 650.5706176757812 |
Other Alternatives
Some other alternatives to these three approaches could include:
In conclusion, this benchmark provides valuable insights into the performance characteristics of different array iteration approaches in modern browsers. By understanding these differences, developers can choose the most suitable approach for their specific use cases.