for (let i = 1; i <= 1000; i++) {
console.log(i);
}
[Array(1000)].forEach((val,i,arr) => console.log(i+1));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for loop | |
array.forEach |
Test name | Executions per second |
---|---|
for loop | 47.0 Ops/sec |
array.forEach | 46.7 Ops/sec |
The benchmark defined in the JSON compares two methods for iterating through a sequence of numbers from 1 to 1000 in JavaScript: a traditional for
loop and the Array.prototype.forEach
method. This comparison is helpful for understanding performance differences between commonly used iteration techniques and can aid in making more informed decisions about which to use in different scenarios.
For Loop:
for (let i = 1; i <= 1000; i++) {
console.log(i);
}
for loop
for
loop with an index variable i
that increments from 1 to 1000. The console.log(i)
function outputs the current index during each iteration.Array.forEach:
[...Array(1000)].forEach((val,i,arr) => console.log(i+1));
array.forEach
[...]
with Array(1000)
. The forEach
method iterates over this array, executing the provided callback function, which logs the index plus one (i + 1
), corresponding to the numbers 1 to 1000.The benchmark results indicate the number of executions per second for each method:
Pros:
Array.forEach
, as shown by the benchmark.Cons:
Pros:
Cons:
for
loops, as the benchmark suggests; this can be a significant factor in performance-critical applications.break
or continue
).for
loop is often preferred. For scenarios where code readability and maintainability are paramount, or when dealing with functional constructs, Array.forEach
might be the better choice.For...of Loop: Can be used for iterating over iterable objects. It is less verbose and may provide better readability but may have performance characteristics similar to Array.forEach
.
for (const number of Array.from({ length: 1000 }, (_, i) => i + 1)) {
console.log(number);
}
While Loop: Provides flexibility and can be adjusted according to the loop control.
let i = 1;
while (i <= 1000) {
console.log(i);
i++;
}
Map Method: For a functional style—though not typically used solely for side effects like logging, it can transform an array and retain the courtesy of chaining.
Array.from({ length: 1000 }, (_, i) => i + 1).map(num => console.log(num));
In summary, this benchmark gives insight into the efficiency of traditional versus more modern JavaScript iteration methods, allowing developers to choose the right tool for their particular application context.