function* createGenerator() {
var i;
for (i = 0; i < 100; i++) {
yield i;
}
}
function createClosure() {
var i = 0;
return {
next() {
var result;
if (i < 100) {
result = {
value: i,
done: false
};
} else {
result = {
value: undefined,
done: true
};
}
i++;
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 | 7858.9 Ops/sec |
Closure polyfill | 11631.2 Ops/sec |
Let's break down the provided JSON and explain what's being tested.
Benchmark Definition
The benchmark definition is a JavaScript script that creates two different types of generators:
createGenerator
) that yields values on each iteration.next
method (createClosure
). This is likely a polyfill for older browsers that don't support closures natively.The benchmark script prepares the generators by creating instances and setting up the execution loop.
Test Cases
There are two individual test cases:
Options Compared
In this benchmark, we have two options being compared:
createGenerator
function, which is supported by most modern browsers.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Built-in JavaScript Generator (ES6)
Pros:
Cons:
Closure Polyfill
Pros:
Cons:
Library/ Library Purpose
In this benchmark, there is no external library used. The createGenerator
and createClosure
functions are self-contained and don't rely on any external libraries.
Special JS Feature/Syntax
There's a special JavaScript feature being tested here: generators. Generators allow you to create iterators that can be paused and resumed, which is useful for cooperative multitasking and other use cases.
Keep in mind that this benchmark focuses on the execution speed of generators, rather than their functional capabilities or ease of use.
Other Alternatives
If you're looking for alternatives to generators, you might consider:
These alternatives have their own trade-offs and use cases, but might be worth exploring if you're interested in exploring different approaches to asynchronous programming.