Created
March 3, 2021 00:27
-
-
Save rkaw92/882283fc24f32b46dc6f589b1e446e31 to your computer and use it in GitHub Desktop.
Node benchmark: plain ReadableStream vs. asyncIterator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Readable } = require('stream'); | |
const ITEM_COUNT = 10 * 1000 * 1000; | |
class EventStream extends Readable { | |
constructor(count) { | |
super({ objectMode: true }); | |
this.remainingCount = count; | |
} | |
_read(_size) { | |
let result = true; | |
do { | |
result = this.push({ countdown: this.remainingCount }); | |
this.remainingCount = this.remainingCount - 1; | |
} while (result === true && this.remainingCount > 0); | |
if (this.remainingCount === 0) { | |
this.push(null); | |
} | |
} | |
} | |
// Stream + AsyncIterator: takes 4.3s on my machine | |
const start1 = process.hrtime.bigint(); | |
const myStream = new EventStream(ITEM_COUNT); | |
let processedItems = 0; | |
(async function() { | |
for await (item of myStream) { | |
processedItems += 1; | |
} | |
const end1 = process.hrtime.bigint(); | |
console.log('Iterator-based: processed %d, elapsed %d ns', processedItems, end1 - start1); | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Readable } = require('stream'); | |
const ITEM_COUNT = 10 * 1000 * 1000; | |
class EventStream extends Readable { | |
constructor(count) { | |
super({ objectMode: true }); | |
this.remainingCount = count; | |
} | |
_read(_size) { | |
let result = true; | |
do { | |
result = this.push({ countdown: this.remainingCount }); | |
this.remainingCount -= 1; | |
} while (result === true && this.remainingCount > 0); | |
if (this.remainingCount === 0) { | |
this.push(null); | |
} | |
} | |
} | |
// Stream only - takes 1.4s on my machine: | |
const start1 = process.hrtime.bigint(); | |
const myStream = new EventStream(ITEM_COUNT); | |
let processedItems = 0; | |
myStream.on('data', function() { | |
processedItems += 1; | |
}); | |
myStream.on('end', function() { | |
const end1 = process.hrtime.bigint(); | |
console.log('Stream-only: processed %d, elapsed %d ns', processedItems, end1 - start1); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: benchmark performed with Node 15.10.0 installed via nvm, on Debian 10.7 amd64 running on Intel Core i7-5500U.