function* range(a, b) {
do {
yield a;
} while ((a += 1) < b);
}
let total = 0;
for (let ii of range(0,100000)) {
total += ii;
}
function range(a, b) {
let arr = [];
for (i = a; i < b; i++) {
arr.push(i);
}
return arr;
}
let total = 0;
for (let ii of range(0, 100000)) {
total += ii;
}
function range(a, b) {
let arr = [];
return arr;
}
let total = 0;
for (i = 0; i < 100000; i++) {
total += i;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
generator | |
array | |
for |
Test name | Executions per second |
---|---|
generator | 360.6 Ops/sec |
array | 431.6 Ops/sec |
for | 730.3 Ops/sec |
I'll break down the provided JSON and explain what's being tested.
Benchmark Definition
The benchmark is defined by a script that generates an array of numbers using three different approaches: range
generator, array creation, and traditional for loop. The script also calculates the sum of these numbers.
Approaches
push
method to add elements to the array. The sum is calculated after creating the array.i
) and adds its value to a running total.Pros and Cons
Library Used
None of the approaches explicitly use any JavaScript libraries beyond the built-in Array
and Math
.
Special JS Feature/Syntax No special JavaScript features or syntax are used in these approaches. They primarily rely on standard iteration constructs like generators, for loops, and array methods.
Other Alternatives
For generating a range of numbers, other alternatives could include:
Array.from()
with an iterator function.Map
or Set
objects to accumulate the sum (though this might be slower than traditional arrays).However, these approaches would likely exhibit different performance characteristics and memory usage patterns compared to the ones described in the benchmark.