function* range(n) {
var i;
for (i = 0; i < n; i++) {
yield n;
}
}
let total = 0;
for (let ii of range(100000)) {
total += ii;
}
function range(n) {
let arr = [];
for (i = 0; i < n; i++) {
arr.push(i);
}
return arr;
}
let total = 0;
for (let ii of range(100000)) {
total += ii;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
generator | |
array |
Test name | Executions per second |
---|---|
generator | 226.5 Ops/sec |
array | 733.6 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Definition
The benchmark is comparing two approaches: using a generator and using an array to generate a sequence of numbers.
Options Compared
function*
syntax)Pros and Cons of Each Approach
Using Generators:
Pros:
Cons:
yield
keywordUsing Arrays:
Pros:
Cons:
Library/Function Used
In this benchmark, no libraries or external functions are used. The generator function is a built-in JavaScript feature.
Special JS Features/Syntax
The benchmark uses the function*
syntax for generators, which was introduced in ECMAScript 2015 (ES6). This allows developers to create generator functions that can be used to iterate over sequences of values.
Alternative Approaches
Other approaches to generating sequences could include:
for...of
loop with an array expressionArray.prototype.map()
and Array.prototype.reduce()
methodsHowever, these alternatives are not tested in this benchmark.
Benchmark Preparation Code
The preparation code is empty for both test cases, which means that no additional setup or initialization is required before running the benchmarks.
Latest Benchmark Result
The latest benchmark result shows that the array approach outperforms the generator approach. The Opera browser execution rate for the array test is higher than the generator test, indicating that arrays may be faster in this specific scenario. However, it's essential to note that performance can vary depending on the specific use case and hardware configuration.