Skip to content

Commit a7173ff

Browse files
committed
Avoid unnecessary buffer copy in internalWrite
See the code comments for details.
1 parent 0e29718 commit a7173ff

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

packages/open-next/src/http/openNextResponse.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -285,13 +285,20 @@ export class OpenNextNodeResponse extends Transform implements ServerResponse {
285285
}
286286

287287
private _internalWrite(chunk: any, encoding: BufferEncoding) {
288-
const buffer = Buffer.from(chunk, encoding);
288+
// When encoding === 'buffer', chunk is already a Buffer
289+
// and does not need to be converted again.
290+
// @ts-expect-error TS2367 'encoding' can be 'buffer', but it's not in the
291+
// official type definition
292+
const buffer = encoding === "buffer" ? chunk : Buffer.from(chunk, encoding);
289293
this.bodyLength += buffer.length;
290294
if (this.streamCreator?.retainChunks !== false) {
291295
// Avoid keeping chunks around when the `StreamCreator` supports it to save memory
292296
this._chunks.push(buffer);
293297
}
294-
this.push(chunk, encoding);
298+
// We already have the data as a buffer, let's push it as is to avoid
299+
// unnecessary additional conversion down the stream pipeline.
300+
// @ts-expect-error TS2345 'buffer' is not in the official type definition
301+
this.push(buffer, "buffer");
295302
this.streamCreator?.onWrite?.();
296303
}
297304

0 commit comments

Comments
 (0)