const arr = Array(10000).fill(1);
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += i;
}
const arr = Array(10000).fill(1);
let sum = 0;
for (const el of arr) {
sum += el;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
traditional for loop | |
for ... of |
Test name | Executions per second |
---|---|
traditional for loop | 18772.7 Ops/sec |
for ... of | 17825.6 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition
The provided JSON represents a benchmark definition, which is essentially a script that defines a simple task to be performed by different programming approaches. In this case, we have two test cases:
for
loop with an index variable (i
) that increments from 0 to the length of an array.for...of
loop that iterates over the same array without an explicit index variable.Options Compared
The options being compared are:
for
loop with an index variable (i
)for...of
loop (a newer, more concise syntax introduced in ECMAScript 2015)Pros and Cons of Each Approach
for
Loopi
) if needed.for...of
.for...of
Loopfor
loops.Libraries and Special JS Features
Neither test case uses any libraries or special JavaScript features beyond what's standard in ECMAScript 2015 (ES6). The for...of
loop is simply a more concise way of iterating over an array without having to declare a separate index variable.
Other Alternatives
If you're interested in exploring other alternatives, here are a few options:
for
loops and for...of
loops.forEach()
method for a more concise and expressive solution.In conclusion, MeasureThat.net's benchmark helps you compare the performance of traditional for
loops versus the newer, more concise for...of
loop. While both approaches have their pros and cons, for...of
is generally considered a better choice due to its readability and reduced chance of off-by-one errors.