const arr = new Array(10000)
for (let i = 0; i < arr.length; i++) {
console.log(i);
}
const arr = new Array(10000)
const len = arr.length
for (let i = 0; i < len; i++) {
console.log(i);
}
let i = 0;
const arr = new Array(10000)
while (i < arr.length) {
console.log(i);
i++;
}
let i = 0;
const arr = new Array(10000)
const len = arr.length
while (i < len) {
console.log(i);
i++;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
for len | |
while | |
while len |
Test name | Executions per second |
---|---|
for | 47.2 Ops/sec |
for len | 47.1 Ops/sec |
while | 47.1 Ops/sec |
while len | 47.5 Ops/sec |
The provided benchmark on MeasureThat.net is testing various looping methods in JavaScript to determine their performance in terms of execution speed. Below is a breakdown of each test case, the comparison of options, pros and cons, and considerations.
For Loop:
const arr = new Array(10000);
for (let i = 0; i < arr.length; i++) {
console.log(i);
}
for
loop.For Loop with Length Caching:
const arr = new Array(10000);
const len = arr.length;
for (let i = 0; i < len; i++) {
console.log(i);
}
for
loop where the length of the array is stored in a variable (len
).While Loop:
let i = 0;
const arr = new Array(10000);
while (i < arr.length) {
console.log(i);
i++;
}
while
loop that continues until the condition is no longer true.While Loop with Length Caching:
let i = 0;
const arr = new Array(10000);
const len = arr.length;
while (i < len) {
console.log(i);
i++;
}
while
loop with cached length.for
loop with length caching.The benchmark results show the number of executions per second for each method:
For Loop:
For Loop with Length Caching:
While Loop:
for
loop, with repeated access to the array's length property.While Loop with Length Caching:
for
version.console.log()
, which may affect timing depending on the environment. This could skew benchmark results, as logging can be relatively slow.Array.forEach()
: A method that executes a provided function once for each array element. This can be cleaner and more readable but is generally slower than traditional loops for performance-critical applications.for...of
Loop: A newer iteration syntax that provides a simpler way to iterate over iterables but can have slight performance drawbacks compared to traditional loops in critical scenarios.map
, filter
, and reduce
, though often less performant for large datasets compared to traditional loops, they offer elegant and expressive coding patterns.In summary, for intensive operations on arrays, the for
loop with length caching and the while
loop with length caching tend to perform better. Meanwhile, readability and maintainability are crucial factors when choosing loop types, so the best option can vary based on specific project requirements.