-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path20-memory-allocations.ts
More file actions
295 lines (265 loc) · 9.05 KB
/
Copy path20-memory-allocations.ts
File metadata and controls
295 lines (265 loc) · 9.05 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
/**
* Memory Profiling: Per-Operation Allocations
*
* Measures heap allocations and GC pressure per streaming operation.
* Compares New Streams vs Web Streams across five scenarios.
*
* Run with:
* node --expose-gc --import tsx/esm benchmarks/20-memory-allocations.ts
*/
import { run, bench, do_not_optimize, summary, boxplot } from 'mitata';
import { Stream } from '../src/index.js';
import type { Transform, Writer } from '../src/index.js';
import { generateChunks } from './utils.js';
// ============================================================================
// Test data (pre-allocated to isolate streaming machinery overhead)
// ============================================================================
const CHUNK_SIZE = 4 * 1024; // 4KB
const SMALL = 1000; // 1000 chunks = 4MB
const LARGE = 10_000; // 10000 chunks = 40MB
const BCAST = 500; // 500 chunks = 2MB
const smallChunks = generateChunks(CHUNK_SIZE, SMALL);
const largeChunks = generateChunks(CHUNK_SIZE, LARGE);
const bcastChunks = generateChunks(CHUNK_SIZE, BCAST);
// ============================================================================
// Transforms (identical work in both APIs)
// ============================================================================
const xor: Transform = (chunks) => {
if (chunks === null) return null;
return chunks.map((c) => {
const out = new Uint8Array(c.length);
for (let i = 0; i < c.length; i++) out[i] = c[i] ^ 0x42;
return out;
});
};
function xorTS(): TransformStream<Uint8Array, Uint8Array> {
return new TransformStream({
transform(chunk, ctrl) {
const out = new Uint8Array(chunk.length);
for (let i = 0; i < chunk.length; i++) out[i] = chunk[i] ^ 0x42;
ctrl.enqueue(out);
},
});
}
// ============================================================================
// Helpers
// ============================================================================
function webReadable(chunks: Uint8Array[]): ReadableStream<Uint8Array> {
let i = 0;
return new ReadableStream({
pull(ctrl) {
if (i >= chunks.length) { ctrl.close(); return; }
ctrl.enqueue(chunks[i++]);
},
});
}
async function consumeWeb(stream: ReadableStream<Uint8Array>): Promise<number> {
const reader = stream.getReader();
let total = 0;
while (true) {
const { value, done } = await reader.read();
if (done) break;
total += value!.byteLength;
}
return total;
}
async function consumeNew(readable: AsyncIterable<Uint8Array[]>): Promise<number> {
let total = 0;
for await (const batch of readable) {
for (const c of batch) total += c.byteLength;
}
return total;
}
function nullWriter(): Writer {
let total = 0;
return {
get desiredSize() { return 1; },
async write(c: Uint8Array | string) {
total += typeof c === 'string' ? c.length : c.byteLength;
},
async writev(cs: (Uint8Array | string)[]) {
for (const c of cs) total += typeof c === 'string' ? c.length : c.byteLength;
},
async end() { return total; },
async fail() {},
writeSync(c: Uint8Array | string) {
total += typeof c === 'string' ? c.length : c.byteLength;
return true;
},
writevSync(cs: (Uint8Array | string)[]) {
for (const c of cs) total += typeof c === 'string' ? c.length : c.byteLength;
return true;
},
endSync() { return total; },
failSync() { return true; },
};
}
// ============================================================================
// Scenario 1: Push write/read (1000 x 4KB, HWM=100)
// ============================================================================
boxplot(() => {
summary(() => {
bench('push write/read (new)', function* () {
yield async () => {
const { writer, readable } = Stream.push({ highWaterMark: 100 });
const producing = (async () => {
for (const chunk of smallChunks) await writer.write(chunk);
await writer.end();
})();
let total = 0;
for await (const batch of readable) {
for (const c of batch) total += c.byteLength;
}
await producing;
do_not_optimize(total);
};
}).gc('inner');
bench('push writeSync+ondrain (new)', function* () {
yield async () => {
const { writer, readable } = Stream.push({ highWaterMark: 100 });
const producing = (async () => {
for (const chunk of smallChunks) {
if (!writer.writeSync(chunk)) {
const canWrite = await Stream.ondrain(writer);
if (!canWrite) break;
writer.writeSync(chunk);
}
}
await writer.end();
})();
let total = 0;
for await (const batch of readable) {
for (const c of batch) total += c.byteLength;
}
await producing;
do_not_optimize(total);
};
}).gc('inner');
bench('push write/read (web)', function* () {
yield async () => {
let ctrl!: ReadableStreamDefaultController<Uint8Array>;
const rs = new ReadableStream<Uint8Array>({ start(c) { ctrl = c; } });
const producing = (async () => {
for (const chunk of smallChunks) {
ctrl.enqueue(chunk);
await Promise.resolve();
}
ctrl.close();
})();
const total = await consumeWeb(rs);
await producing;
do_not_optimize(total);
};
}).gc('inner');
});
});
// ============================================================================
// Scenario 2: Pull pipeline with XOR transform
// ============================================================================
boxplot(() => {
summary(() => {
bench('pull + transform (new)', function* () {
yield async () => {
const total = await consumeNew(
Stream.pull(Stream.from(smallChunks), xor),
);
do_not_optimize(total);
};
}).gc('inner');
bench('pull + transform (web)', function* () {
yield async () => {
const result = await consumeWeb(
webReadable(smallChunks).pipeThrough(xorTS()),
);
do_not_optimize(result);
};
}).gc('inner');
});
});
// ============================================================================
// Scenario 3: pipeTo with XOR transform
// ============================================================================
boxplot(() => {
summary(() => {
bench('pipeTo + transform (new)', function* () {
yield async () => {
const w = nullWriter();
const total = await Stream.pipeTo(
Stream.from(smallChunks), xor, w,
);
do_not_optimize(total);
};
}).gc('inner');
bench('pipeTo + transform (web)', function* () {
yield async () => {
let total = 0;
const ws = new WritableStream<Uint8Array>({
write(chunk) { total += chunk.byteLength; },
});
await webReadable(smallChunks).pipeThrough(xorTS()).pipeTo(ws);
do_not_optimize(total);
};
}).gc('inner');
});
});
// ============================================================================
// Scenario 4: Broadcast / tee (2 consumers, 500 x 4KB)
// ============================================================================
boxplot(() => {
summary(() => {
bench('broadcast 2 consumers (new)', function* () {
yield async () => {
const { writer, broadcast } = Stream.broadcast({ highWaterMark: 100 });
const c1 = broadcast.push();
const c2 = broadcast.push();
const producing = (async () => {
for (const chunk of bcastChunks) await writer.write(chunk);
await writer.end();
})();
const [r1, r2] = await Promise.all([
consumeNew(c1),
consumeNew(c2),
producing,
]);
do_not_optimize(r1 + r2);
};
}).gc('inner');
bench('tee 2 consumers (web)', function* () {
yield async () => {
const [s1, s2] = webReadable(bcastChunks).tee();
const [r1, r2] = await Promise.all([
consumeWeb(s1),
consumeWeb(s2),
]);
do_not_optimize(r1 + r2);
};
}).gc('inner');
});
});
// ============================================================================
// Scenario 5: Large volume pull (10000 x 4KB = 40MB)
// ============================================================================
boxplot(() => {
summary(() => {
bench('large pull 40MB (new)', function* () {
yield async () => {
const total = await consumeNew(
Stream.pull(Stream.from(largeChunks), xor),
);
do_not_optimize(total);
};
}).gc('inner');
bench('large pull 40MB (web)', function* () {
yield async () => {
const result = await consumeWeb(
webReadable(largeChunks).pipeThrough(xorTS()),
);
do_not_optimize(result);
};
}).gc('inner');
});
});
// ============================================================================
console.log('Memory Allocation Profiling: New Streams vs Web Streams');
console.log('(heap and gc rows require --expose-gc)\n');
await run();