function* range(lo, hi) {
for (let i = lo; i < hi; i++) {
yield i;
}
}
window.arr = new Array(10000);
for (const i of range(0, 10000)) {
arr[i] = i;
}
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
let sum = 0;
for (const i of range(0, arr.length)) {
sum += arr[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
range |
Test name | Executions per second |
---|---|
for | 422.0 Ops/sec |
range | 688.3 Ops/sec |
Let's break down the provided JSON and explain what's being tested, compared, and the pros/cons of each approach.
Benchmark Definition
The benchmark is designed to compare the performance of two approaches: traditional for
loop and the range()
function.
range()
function is a generator function that yields numbers from a specified start value (lo
) up to, but not including, a stop value (hi
). In this case, it's used to generate an array of numbers from 0 to 9,999.arr
with 10,000 elements and assigns the generated numbers from range()
to these elements.Options Compared
There are two options being compared:
for
loop: This is a standard way of iterating over an array in JavaScript.range()
function: A generator function that generates numbers on-the-fly, eliminating the need for explicit array creation and indexing.Pros and Cons of Each Approach
for
loop:range()
function:Library/Functionality Used
The range()
function is a custom implementation, likely created for this benchmark. Its purpose is to generate numbers on-the-fly, allowing for dynamic array creation and indexing without the need for explicit array allocation.
Special JS Feature/Syntax
There is no special JavaScript feature or syntax being tested in this benchmark. However, it's worth noting that generator functions like range()
are a relatively new addition to JavaScript (introduced in ECMAScript 2015) and may not be supported by older browsers.
Other Alternatives
If the benchmark were to compare other approaches, some alternatives could include:
Array.prototype.fill()
or Array.prototype.set()
to create an array with initial values.range
function for generating arrays.Set
or Map
data structure instead of an array.Keep in mind that the choice of approach often depends on the specific requirements and constraints of the project.