Skip to content

Instantly share code, notes, and snippets.

@yume-chan
Last active March 18, 2022 05:35
Show Gist options
  • Save yume-chan/fb191d712d2972b3a1bb7fb271c2d3cc to your computer and use it in GitHub Desktop.
Save yume-chan/fb191d712d2972b3a1bb7fb271c2d3cc to your computer and use it in GitHub Desktop.
import { ReadableStream, WritableStream } from 'stream/web';
async function measure(name, func) {
for (let i = 0; i < 5; i++) {
const start = Date.now();
await func();
console.log(`${name}: ${Date.now() - start}ms`);
}
}
const count = 100000;
await measure('stream', async () => {
let i = 0;
let sum = 0;
await new ReadableStream({
pull(controller) {
if (i < count) {
controller.enqueue(i);
i++;
} else {
controller.close();
}
}
}, { highWaterMark: 1 }).pipeTo(new WritableStream({
write(chunk) {
sum += chunk;
},
}, { highWaterMark: 10000 }))
console.log(sum);
});
await measure('call', () => {
let sum = 0;
function write(chunk) {
sum += chunk;
}
for (let i = 0; i < count; i++) {
write(i);
}
console.log(sum);
});
const script = document.createElement('script');
script.src = 'https://unpkg.com/web-streams-polyfill/dist/polyfill.min.js';
script.onload = async () => {
console.log(ReadableStream);
async function measure(name, func) {
const start = Date.now();
await func();
console.log(`${name}: ${Date.now() - start}ms`);
}
const count = 100000;
await measure('stream', async () => {
let sum = 0;
await new ReadableStream({
start(controller) {
for (let i = 0; i < count; i++) {
controller.enqueue(i);
}
controller.close();
}
}).pipeTo(new WritableStream({
write(chunk) {
sum += chunk;
},
}))
console.log(sum);
});
await measure('call', () => {
let sum = 0;
function write(chunk) {
sum += chunk;
}
for (let i = 0; i < count; i++) {
write(i);
}
console.log(sum);
});
}
document.head.appendChild(script);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment