var array = new Array(100);
for (var i = 0; i < array.length; i++) {
array[i];
}
array.forEach(function(i) {
array[i];
});
var i = 0;
while (i < 100) {
array[i];
i++;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For | |
Foreach | |
While |
Test name | Executions per second |
---|---|
For | 100323.0 Ops/sec |
Foreach | 2434194.2 Ops/sec |
While | 197508.5 Ops/sec |
Let's break down the provided benchmark test cases and explain what's being tested.
Benchmark Definition
The JSON defines a simple JavaScript microbenchmark that compares three different loops:
for
loopforEach
loopwhile
loopAll three loops aim to iterate over an array of 100 elements, performing some operation on each element (in this case, simply accessing the element using its index).
Script Preparation Code
The script preparation code creates a new array with 100 elements:
var array = new Array(100);
This code is executed before running each test case.
Html Preparation Code
There is no HTML preparation code provided, which means that the benchmark only tests the JavaScript engine's performance and does not consider other factors like page rendering or DOM manipulation.
Test Cases
The three individual test cases are:
For
loop:for (var i = 0; i < array.length; i++) {
array[i];
}
This loop uses a traditional for
loop with an index variable (i
) and increments it manually.
Foreach
loop:array.forEach(function(i) {
array[i];
});
This loop uses the forEach
method, which is a built-in array method that iterates over the elements of an array.
While
loop:var i = 0;
while (i < 100) {
array[i];
i++;
}
This loop uses a traditional while
loop with an index variable (i
) and increments it manually.
Library Used
None of the test cases use any external libraries or frameworks. The forEach
method is a built-in JavaScript method that comes with the language.
Special JS Feature/ Syntax
None of the test cases use any special JavaScript features or syntax beyond what's described above.
Pros and Cons of Different Approaches
Here are some pros and cons of each approach:
for
loop in terms of control flow, but with more flexibility.Other Alternatives
In addition to these three loops, other alternatives for iterating over arrays in JavaScript include:
Array.prototype.map()
Array.prototype.reduce()
for...of
loop (available in modern browsers and Node.js)However, these alternatives are not included in the provided benchmark test cases.
Benchmark Result Interpretation
The latest benchmark result shows the execution speed for each test case on a Mac OS X 10.15.7 system with Chrome 122 browser:
Foreach
loop: 2434194.25 executions per secondWhile
loop: 197508.46875 executions per secondFor
loop: 100322.9765625 executions per secondThe results suggest that the Foreach
loop is the fastest, followed by the For
loop, and then the While
loop. However, the actual performance difference may vary depending on the specific use case and environment.