forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreadable-read-buffered.js
More file actions
54 lines (48 loc) · 1.29 KB
/
Copy pathreadable-read-buffered.js
File metadata and controls
54 lines (48 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
'use strict';
const common = require('../common.js');
const { ReadableStream } = require('node:stream/web');
// Benchmark for reading from a pre-buffered ReadableStream.
// This measures the fast path optimization where data is already
// queued in the controller, avoiding DefaultReadRequest allocation.
const bench = common.createBenchmark(main, {
n: [1e5],
bufferSize: [1, 10, 100, 1000],
});
async function main({ n, bufferSize }) {
let enqueued = 0;
const rs = new ReadableStream({
start(controller) {
// Pre-fill the buffer
for (let i = 0; i < bufferSize; i++) {
controller.enqueue('a');
enqueued++;
}
},
pull(controller) {
// Refill buffer when pulled
const toEnqueue = Math.min(bufferSize, n - enqueued);
for (let i = 0; i < toEnqueue; i++) {
controller.enqueue('a');
enqueued++;
}
if (enqueued >= n) {
controller.close();
}
},
}, {
// Use buffer size as high water mark to allow pre-buffering
highWaterMark: bufferSize,
});
const reader = rs.getReader();
let x = null;
let reads = 0;
bench.start();
while (reads < n) {
const { value, done } = await reader.read();
if (done) break;
x = value;
reads++;
}
bench.end(reads);
console.assert(x);
}