Skip to content

Commit e76e736

Browse files
authored
feat(node-http-handler): improve stream collection performance (#1272)
* feat(node-http-handler): improve stream collection performance * changeset * feat: update stream-collector implementation
1 parent 5060cde commit e76e736

File tree

3 files changed

+34
-12
lines changed

3 files changed

+34
-12
lines changed

.changeset/fluffy-crabs-watch.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@smithy/fetch-http-handler": patch
3+
"@smithy/node-http-handler": patch
4+
---
5+
6+
improve stream collection speed

packages/fetch-http-handler/src/stream-collector.ts

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,20 +17,28 @@ async function collectBlob(blob: Blob): Promise<Uint8Array> {
1717
}
1818

1919
async function collectStream(stream: ReadableStream): Promise<Uint8Array> {
20-
let res = new Uint8Array(0);
20+
const chunks = [];
2121
const reader = stream.getReader();
2222
let isDone = false;
23+
let length = 0;
24+
2325
while (!isDone) {
2426
const { done, value } = await reader.read();
2527
if (value) {
26-
const prior = res;
27-
res = new Uint8Array(prior.length + value.length);
28-
res.set(prior);
29-
res.set(value, prior.length);
28+
chunks.push(value);
29+
length += value.length;
3030
}
3131
isDone = done;
3232
}
33-
return res;
33+
34+
const collected = new Uint8Array(length);
35+
let offset = 0;
36+
for (const chunk of chunks) {
37+
collected.set(chunk, offset);
38+
offset += chunk.length;
39+
}
40+
41+
return collected;
3442
}
3543

3644
function readToBase64(blob: Blob): Promise<string> {

packages/node-http-handler/src/stream-collector/index.ts

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,18 +35,26 @@ const isReadableStreamInstance = (stream: unknown): stream is IReadableStream =>
3535
typeof ReadableStream === "function" && stream instanceof ReadableStream;
3636

3737
async function collectReadableStream(stream: IReadableStream): Promise<Uint8Array> {
38-
let res = new Uint8Array(0);
38+
const chunks = [];
3939
const reader = stream.getReader();
4040
let isDone = false;
41+
let length = 0;
42+
4143
while (!isDone) {
4244
const { done, value } = await reader.read();
4345
if (value) {
44-
const prior = res;
45-
res = new Uint8Array(prior.length + value.length);
46-
res.set(prior);
47-
res.set(value, prior.length);
46+
chunks.push(value);
47+
length += value.length;
4848
}
4949
isDone = done;
5050
}
51-
return res;
51+
52+
const collected = new Uint8Array(length);
53+
let offset = 0;
54+
for (const chunk of chunks) {
55+
collected.set(chunk, offset);
56+
offset += chunk.length;
57+
}
58+
59+
return collected;
5260
}

0 commit comments

Comments
 (0)