var array = new Array(65535).fill(0);
var q = 0;
for (var i = 0; i < array.length; i++) {
q = array[i];
}
for (var i of array) {
q = i;
}
array.forEach((i) => q = i);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for i | |
for..of | |
foreach |
Test name | Executions per second |
---|---|
for i | 182.7 Ops/sec |
for..of | 475.9 Ops/sec |
foreach | 477.4 Ops/sec |
Benchmark Explanation
The provided benchmark, titled "Side effect: for i vs for of vs foreach fix", tests the performance difference between three approaches to iterate over an array:
for
loop: This is the classic way to iterate over an array in JavaScript. The loop variable i
is declared outside the loop, and it increments manually.of
loop: Introduced in ECMAScript 2015 (ES6), this loop allows iterating directly over an array's elements without declaring a separate loop variable.forEach
method: This is a built-in method of arrays that executes a callback function for each element, skipping the need to declare a loop variable.Options Compared
The benchmark compares the performance of these three approaches:
for
loopof
loopforEach
methodPros and Cons of Each Approach
for
loop:of
loop:forEach
method:for
loops or of
loops.Library Usage
In the provided benchmark, no external libraries are used. However, if a library like Lodash (_
) were used in one of the test cases, it would likely be used for its utility functions, such as array iteration helpers.
Special JS Features or Syntax
None are mentioned in this benchmark. However, it's worth noting that other benchmarks may use special features like Set
operations, regular expressions, or async/await to test specific JavaScript capabilities.
Other Alternatives
If you were to write a similar benchmark, you might consider adding additional iterations, variations in array size or complexity, or even testing with different browsers or platforms to further exhaust the performance differences between these approaches.