var arr = [];
for(let i = 0; i < 10000; i++) {
arr.push(Math.random());
}
var arrLength = arr.length;
var sum = 0;
for(const num of arr) {
sum += num;
}
for(let i = 0; i < arrLength; i++) {
sum += arr[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Iterator for loop | |
Index for loop |
Test name | Executions per second |
---|---|
Iterator for loop | 5218.8 Ops/sec |
Index for loop | 6839.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks and explore what's being tested in this particular benchmark.
What is being tested?
The provided JSON represents two individual test cases that compare the performance of different approaches to iterate over an array in JavaScript:
for...of
loop, which creates an iterator object from the array and allows it to be iterated over without exposing its underlying implementation.for
loop with an index variable (i
) to iterate over the array.Options compared
The two approaches are being compared in terms of their performance, measured by the number of executions per second.
Pros and Cons:
Library usage
There is no explicit library used in this benchmark, but the for...of
loop syntax relies on the JavaScript iterator API, which is part of the ECMAScript standard.
Special JS feature or syntax
The test case uses the for...of
loop syntax, which is a relatively recent addition to the JavaScript language (introduced in ECMAScript 2015). This syntax allows for more concise and expressive iteration over arrays and other iterable objects.
Other alternatives
If you're interested in exploring alternative approaches, here are a few options:
Keep in mind that these alternatives may not be as performant or memory-efficient as the for...of
loop syntax used in this benchmark.