var count = 1000 * 1000
var data = [];
do {
data.push(count);
} while(--count);
var length = data.length;
for (var index = 0; index < length; index++) {
var obj = data[index];
obj == obj;
}
for (var obj of data) {
obj == obj;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
for of |
Test name | Executions per second |
---|---|
for | 969.0 Ops/sec |
for of | 383.2 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Overview
The benchmark compares two approaches for iterating over an array: traditional for
loop and for...of
loop. The test case is simple: it pushes 1,000,000 numbers into an array and then iterates over the array using both loops, checking if each object is equal to itself.
Script Preparation Code
The script preparation code creates a large array data
with 1,000,000 elements, all set to the value count
, which is initialized to a large number. This array will be used for testing both loop approaches.
Html Preparation Code
There is no HTML preparation code provided, so we can assume that it's not necessary for this benchmark.
Library and Special JS Features
In this benchmark, there is no explicit library mentioned. However, the for...of
loop is a built-in JavaScript feature introduced in ECMAScript 2015 (ES6). It allows iterating over arrays without the need for an index variable.
The use of obj == obj
inside the loops is also worth noting. This check is essentially a no-op and will always return true, as any object in JavaScript has itself as its own reference value. However, this test case is not really about performance but rather about verifying that both loop approaches can execute without errors.
Options Compared
Two options are compared:
for
loop: This approach uses an explicit index variable to iterate over the array.for...of
loop: This approach uses a more modern and concise syntax to iterate over arrays, where each iteration is bound to a value in the array.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
for
loopfor...of
loopBenchmark Results
The latest benchmark results show that the for...of
loop outperforms the traditional for
loop on this specific test case. The execution rate for for...of
is significantly higher, at 1088 executions per second, compared to 43 executions per second for for
.
Keep in mind that this performance difference might be due to various factors, including:
Other Alternatives
If you're interested in exploring other alternatives or variations on these loop approaches, here are a few options to consider:
while
loops or even more specialized libraries or frameworks.I hope this explanation helps you understand the benchmark and its results!