diff --git a/.changeset/olive-cars-count.md b/.changeset/olive-cars-count.md new file mode 100644 index 000000000..6d2933d94 --- /dev/null +++ b/.changeset/olive-cars-count.md @@ -0,0 +1,5 @@ +--- +"@opennextjs/aws": patch +--- + +perf: avoid unnecessary buffer copy in internalWrite diff --git a/packages/open-next/src/http/openNextResponse.ts b/packages/open-next/src/http/openNextResponse.ts index 4a521e760..3a8187950 100644 --- a/packages/open-next/src/http/openNextResponse.ts +++ b/packages/open-next/src/http/openNextResponse.ts @@ -285,13 +285,18 @@ export class OpenNextNodeResponse extends Transform implements ServerResponse { } private _internalWrite(chunk: any, encoding: BufferEncoding) { - const buffer = Buffer.from(chunk, encoding); + // When encoding === 'buffer', chunk is already a Buffer + // and does not need to be converted again. + // @ts-expect-error TS2367 'encoding' can be 'buffer', but it's not in the + // official type definition + const buffer = encoding === "buffer" ? chunk : Buffer.from(chunk, encoding); this.bodyLength += buffer.length; if (this.streamCreator?.retainChunks !== false) { // Avoid keeping chunks around when the `StreamCreator` supports it to save memory this._chunks.push(buffer); } - this.push(chunk, encoding); + // No need to pass the encoding for buffers + this.push(buffer); this.streamCreator?.onWrite?.(); }