var count = 1000 * 1000
var data = [];
do {
data.push(count--);
} while(count);
let sum = 0;
for (const obj of data) {
sum += obj;
}
let sum = 0;
for (let index = 0; index < data.length; index++) {
sum += data[index];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
for of |
Test name | Executions per second |
---|---|
for | 56.7 Ops/sec |
for of | 5.9 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Overview
The benchmark compares two approaches for iterating over an array: traditional for
loops versus using the for...of
loop syntax. The test case uses JavaScript, which is used as a programming language to measure performance.
Script Preparation Code
The script preparation code sets up the benchmark by:
data
with 1 million elements.count
initialized to 0 and set to decrement every time through the loop.This code initializes the test environment, creating a scenario where both for
loops will iterate over the same data structure.
Html Preparation Code
There is no HTML preparation code provided, which means that the benchmark does not consider factors like rendering or user interaction.
Options Being Compared
The two options being compared are:
for
loop: This approach uses a traditional for
loop with an incrementing counter (count
) to iterate over the array.for...of
loop syntax: This approach uses the new for...of
loop syntax, which iterates directly over the elements of an array.Pros and Cons
Here are some pros and cons for each approach:
for
loop:for...of
loop syntax:Library Used
There is no specific library used in this benchmark. However, some JavaScript engines like V8 (used by Google Chrome) provide optimizations for for...of
loops that can lead to better performance compared to traditional for
loops.
Special JS Feature or Syntax
The benchmark uses the new for...of
loop syntax, which is a relatively recent addition to JavaScript. This syntax allows iterating over arrays, objects, and other iterable data structures in a concise way.
Other Alternatives
If you're looking for alternatives to these approaches, consider:
Keep in mind that the choice of approach depends on the specific use case and performance requirements. The for...of
loop syntax is often a good choice for iterating over arrays due to its concise nature, but traditional for
loops may still be preferred when fine-grained control over iteration is necessary.