var array = Array.from({length: 5000});
var t;
var len = array.length;
for (let i = 0; i < len; i++) {
t = array[i];
}
array.forEach(function(v, i) {
t = v;
});
for (var v of array) {
t = v;
}
for (var [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 | 91386.4 Ops/sec |
foreach | 20913.7 Ops/sec |
for..of | 22667.4 Ops/sec |
for..of over entries | 13986.8 Ops/sec |
The benchmark provided is designed to compare the performance of different looping constructs in JavaScript when iterating over an array with a large number of elements. Specifically, it tests four different approaches to looping: the traditional for
loop, the forEach
method, the for..of
loop, and the for..of
loop used in combination with the entries()
method.
for Loop
for
loop that accesses elements via an index.forEach Method
for
loops, as it abstracts away the loop mechanics.for
loop, especially for large arrays, due to the overhead of function calls.break
or continue
).for..of Loop
for
loop.for
loop, but usually better than forEach
.for..of over Entries
entries()
method, which returns an iterator with [index, value]
pairs for each element in the array, and iterates over it using for..of
.The benchmark results show the Executions Per Second for each of the tests in a Firefox environment on macOS.
for
loop demonstrates the highest performance at 91,386.375 executions per second, indicating that it is the fastest for large arrays.for..of
loop performs reasonably well with 22,667.41, being better than both forEach
and for..of over entries
.forEach
posts 20,913.73, showcasing decent readability but lesser performance.for..of over entries
option is the slowest with 13,986.80, primarily due to the overhead of managing both the index and value.While the benchmark focuses on these specific looping constructs, JavaScript offers additional alternatives for iterating over arrays, such as:
map(), filter(), and reduce(): These methods can transform or derive new data from arrays, and while they offer great power and succinctness, they generally come with a performance cost compared to traditional loops.
Classic while Loop: Another basic looping construct that can be used but is more verbose and rarely outperforms the for
loop.
Typed Arrays: When dealing with numerical data, typed arrays can show improved performance due to lower overhead in memory handling and can be iterated using similar patterns as above.
In summary, the benchmark demonstrates that the traditional for
loop consistently provides the best performance for large datasets in JavaScript, while the other constructs offer varying trade-offs in terms of readability and overhead. These insights can guide developers in selecting the appropriate looping strategy based on the needs of their specific use cases.