var array = Array.from({length: 100});
var t;
for (let i = 0; i < array.length; i++) {
t = array[i];
}
array.forEach(function(v, i) {
t = v;
});
for (const v of array) {
t = v;
}
for (const [i, v] of array.entries()) {
t = v;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
foreach | |
for..of | |
for..of over entries |
Test name | Executions per second |
---|---|
for | 72006.3 Ops/sec |
foreach | 171216.4 Ops/sec |
for..of | 171911.9 Ops/sec |
for..of over entries | 159427.1 Ops/sec |
Let's break down the provided benchmark definition and test cases to understand what is being tested.
What is being tested?
The main goal of this benchmark is to compare the performance of four different loop constructs in JavaScript:
for
loopforEach
method (a built-in array method)for...of
loop with a variable declarationfor...of
loop with an iterator object and .entries()
methodThese loops will be used to iterate over the same array, accessing its elements.
Options compared
The four options being compared are:
for
loop: A manual loop construct that uses a counter variable (i
) to access array elements.forEach
method: A built-in method that executes a function once for each element in an array.for...of
loop with variable declaration: A newer loop construct that iterates over the elements of an array using a single statement.for...of
loop with iterator object and .entries()
method: Another variant of the for...of
loop, which uses an iterator object to access the array's elements.Pros and cons
Here are some general pros and cons for each option:
for
loop:forEach
method:for...of
loop with variable declaration:for...of
loop with iterator object and .entries()
method:for...of
loop, still concise.Library usage
In this benchmark, none of the libraries are explicitly mentioned. However, it's worth noting that some modern browsers may use internal implementations of these loop constructs that might have performance differences.
Special JavaScript features or syntax
None of the test cases explicitly use special JavaScript features like async/await, arrow functions, or classes.
Other alternatives
For similar benchmarking purposes, other options could be considered:
while
loopdo...while
loopconst [i, v] = array
)let i = 0; while(i < array.length) { ... }
These alternatives might be worth exploring in a separate benchmark to compare their performance with the traditional loop constructs.
Overall, this benchmark aims to evaluate the performance of different loop constructs in JavaScript, providing insights into the efficiency and practicality of each option for common use cases.