Skip to content

Instantly share code, notes, and snippets.

@rkaw92
Created March 3, 2021 00:27
Show Gist options
  • Save rkaw92/882283fc24f32b46dc6f589b1e446e31 to your computer and use it in GitHub Desktop.
Save rkaw92/882283fc24f32b46dc6f589b1e446e31 to your computer and use it in GitHub Desktop.
Node benchmark: plain ReadableStream vs. asyncIterator
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);
})();
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);
});
@rkaw92
Copy link
Author

rkaw92 commented Mar 3, 2021

Note: benchmark performed with Node 15.10.0 installed via nvm, on Debian 10.7 amd64 running on Intel Core i7-5500U.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment