var array = Array.from(Array(1000).keys(), n => n + 1);
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
for (const item of array) {
console.log(item);
}
array.forEach((item) => console.log(item));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
for...of | |
Array.forEach |
Test name | Executions per second |
---|---|
for | 65.0 Ops/sec |
for...of | 58.3 Ops/sec |
Array.forEach | 61.9 Ops/sec |
Overview of the Benchmark
The provided JSON represents a JavaScript microbenchmarking test, where three different approaches are compared: for
, for...of
, and Array.forEach
. The benchmark is designed to measure the performance of these constructs in a loop.
Approaches Compared
for
: This approach uses a traditional for
loop with an index variable i
.for...of
: This approach uses a for...of
loop, which iterates over the elements of an array without a traditional index variable.Array.forEach
: This approach uses the forEach
method on the array
object to iterate over its elements.Pros and Cons
for
: Pros: Simple, easy to understand, and well-supported by all browsers. Cons: May be slower due to the overhead of checking the loop variable against the array length.for...of
: Pros: More modern, concise, and expressive than traditional for
loops. Cons: Some older browsers may not support this syntax, and it can be less efficient in some cases.Array.forEach
: Pros: Simplifies iteration over arrays, easy to read, and widely supported. Cons: May have overhead due to the method call and potential array resizing.Library and Special Features
In this benchmark, no special JavaScript features or libraries are used beyond the standard JavaScript language and built-in Array
object methods (forEach
, from()
, etc.). However, it's essential to note that some browsers may have additional features or optimizations enabled in their rendering engines.
Other Alternatives
While not directly comparable to the approaches listed above, other iteration methods exist:
while
loops: Can be used for iteration over arrays or any other iterable.map()
, filter()
, and reduce()
methods: These are often used for array transformations, filtering, and aggregation but can also be used in a loop context.Benchmark Results
The latest benchmark results show that:
for
: Provides the most executions per second (65.04) on this platform.Array.forEach
: Offers slightly lower execution rates compared to for
.for...of
: Has the lowest execution rate, although it is still more efficient than older browsers might have been.These results are specific to this particular setup and platform (Windows, Chrome 80). The benchmark is designed to be run on multiple platforms and browsers to gain a better understanding of each approach's performance in different scenarios.