const array = Array.from({length: 10000});
let t;
for (let i = 0; i < array.length; i++) {
t = array[i];
}
array.forEach((v) => {
t = v;
});
for (const v of array) {
t = v;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
foreach | |
for..of |
Test name | Executions per second |
---|---|
for | 1839.6 Ops/sec |
foreach | 1885.0 Ops/sec |
for..of | 1881.7 Ops/sec |
The benchmark represented in the provided JSON is designed to compare the performance of different loop constructs in JavaScript: traditional for
loops, the forEach
method, and for..of
loops. Here’s a breakdown of what is being tested:
for
Loop:
for (let i = 0; i < array.length; i++) {
t = array[i];
}
This traditional loop initializes a counter, checks the condition, and accesses each element by its index.
Pros:
Cons:
forEach
Method:
array.forEach((v) => {
t = v;
});
This method takes a callback function which is executed for each element in the array.
Pros:
Cons:
for
loop since it involves function calls for every iteration.for..of
Loop:
for (const v of array) {
t = v;
}
This syntax allows iteration over iterable objects and provides the value directly.
Pros:
break
and continue
.Cons:
for
loop.The results provided indicate that the for
loop had the highest performance, with an execution rate of approximately 1554.76 executions per second. The forEach
method came in second at about 1531.27, followed closely by for..of
at around 1527.50. This data showcases the expected performance characteristics—though modern JavaScript engines optimize these patterns significantly, traditional for
loops often remain the fastest.
When evaluating the best loop construct to use, consider the context and requirements of your code.
When to Use Each:
for
when performance is critical and you need full control over the index, especially in scenarios with large datasets.forEach
for cleaner and more readable code where performance is not the primary concern.for..of
when dealing with collections that are not inherently array-like, such as Map
or Set
, or when readability is a priority.Alternatives:
map
, filter
, and other Array methods provide functional paradigms for transforming arrays but create new arrays as output. These can be slower but may improve code clarity for developers familiar with functional programming techniques. Ultimately, performance testing and profiling in the specific context of your application should guide the choice of method for array iteration.