-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path09-sync-async-comparison.ts
More file actions
365 lines (319 loc) · 12.1 KB
/
Copy path09-sync-async-comparison.ts
File metadata and controls
365 lines (319 loc) · 12.1 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/**
* Benchmark: Sync vs Async API Comparison
*
* Compares the performance of sync and async APIs when processing
* data that could be handled synchronously (pre-generated arrays).
*
* This benchmark shows when to use:
* - fromSync + pullSync + bytesSync (fully sync path)
* - from + pull + bytes (async path with sync source)
* - from + pull + bytes (async path with async source)
*/
import { Stream } from '../src/index.js';
import type { Transform, SyncTransform } from '../src/index.js';
import {
benchmark,
BenchmarkResult,
formatBytesPerSec,
formatTime,
generateChunks,
} from './utils.js';
interface ThreeWayComparison {
scenario: string;
syncPath: BenchmarkResult;
asyncSyncSource: BenchmarkResult;
asyncAsyncSource: BenchmarkResult;
}
function printThreeWayComparison(comparisons: ThreeWayComparison[]): void {
console.log('\n' + '='.repeat(130));
console.log('BENCHMARK RESULTS - Sync vs Async API Comparison');
console.log('='.repeat(130));
const headers = ['Scenario', 'Sync Path', 'Async (sync src)', 'Async (async src)', 'Sync vs Async', 'Sync vs AsyncGen'];
const colWidths = [28, 16, 16, 16, 16, 16];
console.log(headers.map((h, i) => h.padEnd(colWidths[i])).join(' | '));
console.log(colWidths.map((w) => '-'.repeat(w)).join('-+-'));
for (const c of comparisons) {
const syncStr = c.syncPath.bytesPerSec
? formatBytesPerSec(c.syncPath.bytesPerSec)
: formatTime(c.syncPath.mean);
const asyncSyncStr = c.asyncSyncSource.bytesPerSec
? formatBytesPerSec(c.asyncSyncSource.bytesPerSec)
: formatTime(c.asyncSyncSource.mean);
const asyncAsyncStr = c.asyncAsyncSource.bytesPerSec
? formatBytesPerSec(c.asyncAsyncSource.bytesPerSec)
: formatTime(c.asyncAsyncSource.mean);
const syncVsAsync = c.asyncSyncSource.mean / c.syncPath.mean;
const syncVsAsyncGen = c.asyncAsyncSource.mean / c.syncPath.mean;
const syncVsAsyncStr = syncVsAsync >= 1
? `${syncVsAsync.toFixed(1)}x faster`
: `${(1 / syncVsAsync).toFixed(1)}x slower`;
const syncVsAsyncGenStr = syncVsAsyncGen >= 1
? `${syncVsAsyncGen.toFixed(1)}x faster`
: `${(1 / syncVsAsyncGen).toFixed(1)}x slower`;
const row = [
c.scenario.substring(0, colWidths[0] - 1),
syncStr,
asyncSyncStr,
asyncAsyncStr,
syncVsAsyncStr,
syncVsAsyncGenStr,
];
console.log(row.map((v, i) => v.padEnd(colWidths[i])).join(' | '));
}
console.log('='.repeat(130));
const avgSyncVsAsync = comparisons.reduce((sum, c) => sum + c.asyncSyncSource.mean / c.syncPath.mean, 0) / comparisons.length;
const avgSyncVsAsyncGen = comparisons.reduce((sum, c) => sum + c.asyncAsyncSource.mean / c.syncPath.mean, 0) / comparisons.length;
console.log(`\nAverage speedup of sync path vs async (sync source): ${avgSyncVsAsync.toFixed(1)}x`);
console.log(`Average speedup of sync path vs async (async generator): ${avgSyncVsAsyncGen.toFixed(1)}x`);
console.log('\nRecommendation: Use sync APIs (fromSync, pullSync, bytesSync) when source data is synchronously available.');
}
async function runBenchmarks(): Promise<ThreeWayComparison[]> {
const comparisons: ThreeWayComparison[] = [];
// ============================================================================
// Scenario 1: bytes() consumption
// ============================================================================
console.log('Running: bytes() consumption...');
{
const chunkSize = 8 * 1024;
const chunkCount = 2000;
const totalBytes = chunkSize * chunkCount;
const chunks = generateChunks(chunkSize, chunkCount);
const syncResult = await benchmark(
'Sync Path',
async () => {
const result = Stream.bytesSync(Stream.fromSync(chunks));
if (result.length !== totalBytes) throw new Error('Wrong size');
},
{ totalBytes, minSamples: 30, minTimeMs: 3000 }
);
const asyncSyncResult = await benchmark(
'Async (sync src)',
async () => {
const result = await Stream.bytes(Stream.from(chunks));
if (result.length !== totalBytes) throw new Error('Wrong size');
},
{ totalBytes, minSamples: 30, minTimeMs: 3000 }
);
const asyncAsyncResult = await benchmark(
'Async (async src)',
async () => {
async function* source() {
for (const chunk of chunks) yield chunk;
}
const result = await Stream.bytes(Stream.from(source()));
if (result.length !== totalBytes) throw new Error('Wrong size');
},
{ totalBytes, minSamples: 30, minTimeMs: 3000 }
);
comparisons.push({
scenario: 'bytes() (8KB x 2000)',
syncPath: syncResult,
asyncSyncSource: asyncSyncResult,
asyncAsyncSource: asyncAsyncResult,
});
}
// ============================================================================
// Scenario 2: text() consumption
// ============================================================================
console.log('Running: text() consumption...');
{
const text = 'Hello, World! This is a test. '.repeat(10000);
const textBytes = new TextEncoder().encode(text);
const chunkSize = 1024;
const chunks: Uint8Array[] = [];
for (let i = 0; i < textBytes.length; i += chunkSize) {
chunks.push(textBytes.subarray(i, Math.min(i + chunkSize, textBytes.length)));
}
const totalBytes = textBytes.length;
const syncResult = await benchmark(
'Sync Path',
async () => {
const result = Stream.textSync(Stream.fromSync(chunks));
if (result.length !== text.length) throw new Error('Wrong size');
},
{ totalBytes, minSamples: 30, minTimeMs: 3000 }
);
const asyncSyncResult = await benchmark(
'Async (sync src)',
async () => {
const result = await Stream.text(Stream.from(chunks));
if (result.length !== text.length) throw new Error('Wrong size');
},
{ totalBytes, minSamples: 30, minTimeMs: 3000 }
);
const asyncAsyncResult = await benchmark(
'Async (async src)',
async () => {
async function* source() {
for (const chunk of chunks) yield chunk;
}
const result = await Stream.text(Stream.from(source()));
if (result.length !== text.length) throw new Error('Wrong size');
},
{ totalBytes, minSamples: 30, minTimeMs: 3000 }
);
comparisons.push({
scenario: 'text() (1KB chunks)',
syncPath: syncResult,
asyncSyncSource: asyncSyncResult,
asyncAsyncSource: asyncAsyncResult,
});
}
// ============================================================================
// Scenario 3: Pipeline with transform
// ============================================================================
console.log('Running: Pipeline with identity transform...');
{
const chunkSize = 4 * 1024;
const chunkCount = 1000;
const totalBytes = chunkSize * chunkCount;
const chunks = generateChunks(chunkSize, chunkCount);
const syncTransform: SyncTransform = (batch) => batch;
const asyncTransform: Transform = (batch) => batch;
const syncResult = await benchmark(
'Sync Path',
async () => {
const pipeline = Stream.pullSync(Stream.fromSync(chunks), syncTransform);
const result = Stream.bytesSync(pipeline);
if (result.length !== totalBytes) throw new Error('Wrong size');
},
{ totalBytes, minSamples: 30, minTimeMs: 3000 }
);
const asyncSyncResult = await benchmark(
'Async (sync src)',
async () => {
const pipeline = Stream.pull(Stream.from(chunks), asyncTransform);
const result = await Stream.bytes(pipeline);
if (result.length !== totalBytes) throw new Error('Wrong size');
},
{ totalBytes, minSamples: 30, minTimeMs: 3000 }
);
const asyncAsyncResult = await benchmark(
'Async (async src)',
async () => {
async function* source() {
for (const chunk of chunks) yield chunk;
}
const pipeline = Stream.pull(Stream.from(source()), asyncTransform);
const result = await Stream.bytes(pipeline);
if (result.length !== totalBytes) throw new Error('Wrong size');
},
{ totalBytes, minSamples: 30, minTimeMs: 3000 }
);
comparisons.push({
scenario: 'Transform (4KB x 1000)',
syncPath: syncResult,
asyncSyncSource: asyncSyncResult,
asyncAsyncSource: asyncAsyncResult,
});
}
// ============================================================================
// Scenario 4: Iteration consumption
// ============================================================================
console.log('Running: Iteration consumption...');
{
const chunkSize = 8 * 1024;
const chunkCount = 1000;
const totalBytes = chunkSize * chunkCount;
const chunks = generateChunks(chunkSize, chunkCount);
const syncResult = await benchmark(
'Sync Path',
async () => {
let total = 0;
for (const batch of Stream.pullSync(Stream.fromSync(chunks))) {
for (const chunk of batch) {
total += chunk.length;
}
}
if (total !== totalBytes) throw new Error('Wrong size');
},
{ totalBytes, minSamples: 30, minTimeMs: 3000 }
);
const asyncSyncResult = await benchmark(
'Async (sync src)',
async () => {
let total = 0;
for await (const batch of Stream.from(chunks)) {
for (const chunk of batch) {
total += chunk.length;
}
}
if (total !== totalBytes) throw new Error('Wrong size');
},
{ totalBytes, minSamples: 30, minTimeMs: 3000 }
);
const asyncAsyncResult = await benchmark(
'Async (async src)',
async () => {
async function* source() {
for (const chunk of chunks) yield chunk;
}
let total = 0;
for await (const batch of Stream.from(source())) {
for (const chunk of batch) {
total += chunk.length;
}
}
if (total !== totalBytes) throw new Error('Wrong size');
},
{ totalBytes, minSamples: 30, minTimeMs: 3000 }
);
comparisons.push({
scenario: 'Iteration (8KB x 1000)',
syncPath: syncResult,
asyncSyncSource: asyncSyncResult,
asyncAsyncSource: asyncAsyncResult,
});
}
// ============================================================================
// Scenario 5: Many tiny chunks (extreme async overhead)
// ============================================================================
console.log('Running: Many tiny chunks...');
{
const chunkSize = 64;
const chunkCount = 20000;
const totalBytes = chunkSize * chunkCount;
const chunks = generateChunks(chunkSize, chunkCount);
const syncResult = await benchmark(
'Sync Path',
async () => {
const result = Stream.bytesSync(Stream.fromSync(chunks));
if (result.length !== totalBytes) throw new Error('Wrong size');
},
{ totalBytes, minSamples: 30, minTimeMs: 3000 }
);
const asyncSyncResult = await benchmark(
'Async (sync src)',
async () => {
const result = await Stream.bytes(Stream.from(chunks));
if (result.length !== totalBytes) throw new Error('Wrong size');
},
{ totalBytes, minSamples: 30, minTimeMs: 3000 }
);
const asyncAsyncResult = await benchmark(
'Async (async src)',
async () => {
async function* source() {
for (const chunk of chunks) yield chunk;
}
const result = await Stream.bytes(Stream.from(source()));
if (result.length !== totalBytes) throw new Error('Wrong size');
},
{ totalBytes, minSamples: 30, minTimeMs: 3000 }
);
comparisons.push({
scenario: 'Tiny chunks (64B x 20000)',
syncPath: syncResult,
asyncSyncSource: asyncSyncResult,
asyncAsyncSource: asyncAsyncResult,
});
}
return comparisons;
}
// Main
console.log('Benchmark: Sync vs Async API Comparison');
console.log('Comparing sync path (fromSync + pullSync + bytesSync) vs async path');
console.log('(minimum 30 samples, 3 seconds per test)\n');
runBenchmarks()
.then(printThreeWayComparison)
.catch(console.error);