console.log('Start testing...')
for (let i = 0; i < 100; i += 1) {
console.log(i);
}
new Array(100).fill().forEach((val, index) => console.log(index))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for loop | |
forEach loop |
Test name | Executions per second |
---|---|
for loop | 735.2 Ops/sec |
forEach loop | 783.9 Ops/sec |
Let's dive into the details of this benchmark.
What is being tested?
This benchmark compares the performance of two different ways to iterate over an array: for
loops and forEach
methods.
Description of options being compared:
for
loop with a counter variable (i
) to iterate from 0 to 99, incrementing by 1 each time.forEach
method on an array of 100 elements (created using new Array(100).fill()
), which iterates over the array and executes a callback function for each element.Pros and cons of different approaches:
forEach
methodfor
loops in certain scenarios (e.g., when using modern JavaScript engines)for
loops in some casesOther considerations:
new Array(100).fill()
to create an array with 100 elements. This approach creates a new array with all elements initialized to a default value (in this case, undefined
).forEach
test case, the callback function takes two arguments: val
and index
. The val
parameter corresponds to the actual element in the array, while index
represents its index.forEach
loop outperformed the traditional for
loop on this specific test case. However, performance differences may vary depending on the browser/JavaScript engine used and other factors.Alternative approaches:
for...of
loop, which can be used with arrays or iterable objects.map()
for transformation).Libraries and special JS features: