Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save netroy/5c0698f0ec54ca9ef6cab160605e1f23 to your computer and use it in GitHub Desktop.
Save netroy/5c0698f0ec54ca9ef6cab160605e1f23 to your computer and use it in GitHub Desktop.
Generators VS Async/Await Performance
const co = require('co')
const Benchmark = require('benchmark')
const suite = new Benchmark.Suite
const Generate = () => new Promise(resolve => {
// resolve(1)
setImmediate(() => resolve(1))
// setTimeout(() => resolve(1), 10)
})
const Increment = value => new Promise(resolve => {
// resolve(value + 1)
setImmediate(() => resolve(value + 1))
// setTimeout(() => resolve(value + 1), 10)
})
const Doubleup = value => new Promise(resolve => {
// resolve(value * 2)
setImmediate(() => resolve(value * 2))
// setTimeout(() => resolve(value * 2), 10)
})
suite
.add('co', {
defer: true,
fn: deferred => {
co(function*() {
const v1 = yield Generate()
const v2 = yield Increment(v1)
const r = yield Doubleup(v2)
if (r === 4) deferred.resolve()
else throw new Error(r)
})
}
})
.add('async/await', {
defer: true,
fn: deferred => {
(async () => {
const v1 = await Generate()
const v2 = await Increment(v1)
const r = await Doubleup(v2)
if (r === 4) deferred.resolve()
else throw new Error(r)
})()
}
})
.add('native promises', {
defer: true,
fn: deferred => {
Generate()
.then(v => Increment(v))
.then(v => Doubleup(v))
.then(r => {
if (r === 4) deferred.resolve()
else throw new Error(r)
})
}
})
.on('cycle', event => {
console.log(String(event.target))
})
.on('complete', () => {
console.log('Fastest is ' + suite.filter('fastest').map('name'))
})
.run({
'async': false
})
co x 97,841 ops/sec ±1.77% (78 runs sampled)
async/await x 115,441 ops/sec ±1.38% (79 runs sampled)
native promises x 151,467 ops/sec ±0.76% (82 runs sampled)
Fastest is native promises
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment