var array = Array.from({length: 10000});
var t;
for (let i = 0; i < array.length; 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 | 78753.2 Ops/sec |
foreach | 17307.2 Ops/sec |
for..of | 15883.3 Ops/sec |
for..of over entries | 8067.6 Ops/sec |
The benchmark defined in the provided JSON evaluates the performance of four different looping constructs in JavaScript: the traditional for
loop, the forEach
method, the for..of
loop, and the for..of
loop using the entries()
method. The goal is to compare their speed when iterating over an array with 10,000 elements.
Traditional for loop:
for (let i = 0; i < array.length; i++) {
t = array[i];
}
forEach:
array.forEach(function(v, i) {
t = v;
});
for
loop due to the overhead of function calls.for..of:
for (var v of array) {
t = v;
}
for
loop, depending on the JavaScript engine's optimizations.for..of over entries:
for (var [i, v] of array.entries()) {
t = v;
}
for..of
with the ability to access both index and value.The benchmark results show the number of executions per second for each looping method, indicating how many times each loop could complete in a given time frame. From the results, we see:
for..of
: 2002.74 executions/secforEach
: 2001.37 executions/secfor
: 1978.65 executions/secfor..of over entries
: 1935.81 executions/secWhile the benchmark compares four specific looping constructs, there are other alternatives available in JavaScript for iterating arrays, such as:
Array.map(): Transforms every element in an array and returns a new array. It incurs a performance cost because it creates a new array and expects a return value.
Array.filter(): Used for filtering elements based on a condition, returning a new array with the filtered results. This also involves creating a new array, impacting performance.
While loop: A traditional while
loop can also be used to iterate, providing flexibility but often sacrificing readability for simple iterations.
Reduce: While technically a method for reducing an array to a single value, it can be creatively used for iteration. [ however, it's not an ideal substitute for raw iteration due to its functional nature and overhead ]
In summary, this benchmark provides insights into how different looping constructs perform when processing large arrays in JavaScript. The choice of which loop to use can depend on the context: while performance is critical in tight loops, readability and maintainability might be more important when writing code for larger projects. Understanding these trade-offs can help developers choose the right tool for the job.