Skip to content

Commit a428ff3

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

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

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

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -285,13 +285,22 @@ 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'
293+
? chunk
294+
: Buffer.from(chunk, encoding);
289295
this.bodyLength += buffer.length;
290296
if (this.streamCreator?.retainChunks !== false) {
291297
// Avoid keeping chunks around when the `StreamCreator` supports it to save memory
292298
this._chunks.push(buffer);
293299
}
294-
this.push(chunk, encoding);
300+
// We already have the data as a buffer, let's push it as is to avoid
301+
// unnecessary additional conversion down the stream pipeline.
302+
// @ts-expect-error TS2345 'buffer' is not in the official type definition
303+
this.push(buffer, 'buffer');
295304
this.streamCreator?.onWrite?.();
296305
}
297306

0 commit comments

Comments
 (0)