var array = new Array(1);
for (var i = 0; i < array.length; i++) {
array[i];
}
array.forEach(function(i) {
array[i];
});
for (var i in array) {
array[i];
}
for (var i of array) {
array[i];
}
const length = array.length
for (var i = 0; i < length; i++) {
array[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
foreach | |
for in | |
for..of | |
for (cache length |
Test name | Executions per second |
---|---|
for | 15428524.0 Ops/sec |
foreach | 14520560.0 Ops/sec |
for in | 3287515.5 Ops/sec |
for..of | 9296124.0 Ops/sec |
for (cache length | 16183961.0 Ops/sec |
This benchmark compares the performance of various looping constructs in JavaScript using a small array. Specifically, it tests four different types of loops: for
, forEach
, for..in
, and for..of
, alongside an optimization variation of the traditional for
loop that caches the array's length.
for Loop
for (var i = 0; i < array.length; i++) {
array[i];
}
forEach Loop
array.forEach(function(i) {
array[i];
});
break
or continue
for flow control within the loop, which limits flexibility.for..in Loop
for (var i in array) {
array[i];
}
for..of Loop
for (var i of array) {
array[i];
}
for
and for (cache length)
in terms of raw execution speed, depending on the engine's optimizations.for (cache length) Loop
const length = array.length;
for (var i = 0; i < length; i++) {
array[i];
}
array.length
operation) within the loop, optimizing performance, particularly in larger arrays.for
loop follows closely, performing at about 15.43 million executions per second, also demonstrating efficiency.forEach
loop, while useful for its simplicity, only achieves 14.52 million executions per second.for..of
and for..in
trails significantly, with for..of
at 9.30 million and for..in
at a mere 3.29 million executions per second. The latter is particularly inefficient for arrays due to its nature of iterating over all enumerable properties.while
and do...while
loops, which can also be performant but are less common in modern JavaScript in the context of array iteration.async/await
in combination with for
or forEach
may also be applicable, although that introduces complexity in the form of promises and asynchronous behavior.In performance-critical scenarios, especially when dealing with large arrays, traditional for
loops (both standard and length-cached) outshine their modern counterparts in this specific benchmark. For code readability and ease of use in smaller, less performance-critical scenarios, forEach
or for..of
loops can be excellent choices. However, developers should always consider the trade-offs between performance and code clarity based on the specific use case.