function* createGenerator() {
var i;
for (i = 0; i < 0; i++) {
yield i;
}
}
function createClosure() {
var i = 0;
return {
next() {
var result;
if (i < 0) {
result = {
value: i,
done: false
};
i++;
} else {
result = {
value: undefined,
done: true
};
}
return result;
}
};
}
var gen = createGenerator(),
result;
while (!(result = gen.next()).done) {
window.result = result.value;
}
var gen = createClosure(),
result;
while (!(result = gen.next()).done) {
window.result = result.value;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
ES6 generator | |
Closure polyfill |
Test name | Executions per second |
---|---|
ES6 generator | 14119745.0 Ops/sec |
Closure polyfill | 7197239.0 Ops/sec |
I'll break down the provided benchmark and explain what's being tested, compared, and some pros and cons of each approach.
Benchmark Overview
The benchmark measures the performance difference between two JavaScript approaches: ES6 generators and Closure polyfill (which is essentially a workaround for older browsers that don't support ES6 generators).
Generator with low count of items Benchmark Definition
This definition represents a simple generator function createGenerator
that yields values from 0 to -1. The script preparation code includes both the ES6 generator and a Closure polyfill implementation.
Here's what's being tested:
createGenerator
function is executed in two different ways:while (!(result = gen.next()).done)
).while (!(result = gen.next()).done)
).next()
method of the generated values are called, which essentially measures the performance of each approach.Options Compared
The two main options being compared are:
Pros and Cons
ES6 Generators
Pros:
Cons:
Closure Polyfill
Pros:
Cons:
Library and Special JS Feature
In this benchmark, the createGenerator
function uses some special JavaScript features, such as:
yield
keyword is used to define an iterator. This feature was introduced in ECMAScript 2015 (ES6) and allows for efficient creation of iterators.next()
method is used to iterate over the generator values.The Closure polyfill implementation uses a similar approach, but with some differences in syntax and logic.
Other Alternatives
If you're interested in alternative approaches to creating iterators, here are a few options:
iterable
or async-iterator
.Keep in mind that these alternatives may have different performance characteristics and trade-offs compared to ES6 generators and Closure polyfill.