let arr = Array(1000);
for (let i = 0; i < 1000; i++) {
arr[i];
}
let arr = Array(1000);
arr.forEach(it => {
it;
});
let arr = Array(1000);
for (let it of arr) {
it;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
forloop | |
forEach | |
for...of |
Test name | Executions per second |
---|---|
forloop | 236632.0 Ops/sec |
forEach | 125339.1 Ops/sec |
for...of | 228654.3 Ops/sec |
Measuring the performance of JavaScript loops is an important task, and MeasureThat.net provides a useful platform for benchmarking different approaches.
The provided JSON represents three individual test cases: forloop
, forEach
, and for...of
. These tests aim to measure the performance of creating an array and then iterating over it using three different methods: traditional for
loop, Array.forEach()
method, and for...of
loop.
Let's break down each option:
for
Loop (forloop
):
This approach involves creating a new array with the desired length (1000 in this case) and then using a traditional for
loop to iterate over its elements.
Pros:Cons:
forEach
):
This approach uses the Array.prototype.forEach()
method, which iterates over an array using a callback function.
Pros:for
loops, as it leverages optimized JavaScript engine implementationsCons:
for...of
):
This approach uses a for...of
loop, which iterates over an array using the values()
method.
Pros:for
loops but with improved syntax and readabilityArray.forEach()
, as it's also optimized by modern JavaScript enginesCons:
for
loopsIn the provided benchmark results, we can see that:
forloop
test performed the best, with an average of 236,632 executions per second.forEach
test was slightly slower than the forloop
, but still relatively fast at 228,654 executions per second.for...of
loop performed similarly to the traditional for
loop in terms of speed, around 125,339 executions per second.In summary, the choice between these approaches depends on your specific use case and performance requirements. If you need to iterate over arrays frequently, one of these methods should be suitable for most modern JavaScript environments. However, if you're targeting older browsers or require fine-grained control over iteration variables, traditional for
loops might still be a better choice.
Other alternatives worth mentioning include:
Array.prototype.map()
and then iterating over the resulting array (not used in this benchmark)TypedArray
or Int8Array
for optimized iteration (not used in this benchmark)Keep in mind that performance differences between these approaches can be relatively small, and other factors like memory allocation, garbage collection, and caching might have a more significant impact on overall application performance.