var count = 1000 * 1000
var data = [];
do {
data.push(count--);
} while(count);
let sum = 0;
for (let index = 0; index < data.length; index++) {
sum += data[index];
}
let sum = 0;
for (const obj of data) {
sum += obj;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
for of |
Test name | Executions per second |
---|---|
for | 249.6 Ops/sec |
for of | 97.6 Ops/sec |
Let's break down the provided benchmark definition and test cases to understand what is being tested, compared, and their pros and cons.
Benchmark Definition
The benchmark measures the performance difference between two loop constructs in JavaScript: traditional for
loops versus the more modern and concise for...of
loop syntax. The benchmark creates an array of 1 million elements, initializes a variable sum
to zero, and then uses each loop construct to iterate through the array, adding up the values.
Script Preparation Code
The script preparation code is identical for both loops:
var count = 1000 * 1000;
var data = [];
do {
data.push(count--);
} while (count);
This code creates an array data
with a million elements, each initialized to the value of count
, which starts at 1 million and decrements by 1 in each iteration. The for
loop uses a traditional do-while
loop syntax, while the for...of
loop uses a more modern syntax.
Html Preparation Code
The HTML preparation code is empty for both loops, indicating that the benchmark only measures JavaScript performance and does not consider other factors like browser rendering or network latency.
Test Cases
There are two test cases:
let sum = 0;
for (let index = 0; index < data.length; index++) {
sum += data[index];
}
This loop uses a traditional for
loop with an indexed variable index
.
let sum = 0;
for (const obj of data) {
sum += obj;
}
This loop uses the more modern for...of
loop syntax, which iterates over the elements of an array without an explicit index.
Pros and Cons
for
loops: Pros:for...of
loops: Pros:However, traditional for
loops might be slightly faster and more efficient due to less overhead from the modern loop syntax.
Library Usage
There is no explicit library usage mentioned in the benchmark definition. However, it's worth noting that some libraries like Lodash or Ramda might provide optimized implementation of array iteration, which could potentially affect the benchmark results.
Special JS Feature/ Syntax
The for...of
loop uses a special JavaScript feature: Array Iteration Protocol (AIP). This protocol defines how arrays should be iterated over, and modern browsers follow this protocol for better compatibility and performance. The for...of
loop syntax leverages this AIP to iterate over the elements of an array without requiring an explicit index.
Alternatives
Some alternative loop constructs that could be used in a benchmarking scenario include:
for
loops.Keep in mind that the choice of loop construct depends on the specific requirements and constraints of the benchmarking scenario.