From 745c029e125b4326059ed575ee0180c0544dead3 Mon Sep 17 00:00:00 2001 From: Yaroslav Chuhai Date: Sun, 22 Nov 2026 21:28:30 +0100 Subject: [PATCH] stream: avoid intermediate Blob in stream/consumers arrayBuffer() In node:stream/consumers, arrayBuffer() (also used by buffer() and bytes()) collected stream chunks into a temporary Blob and then read them back out asynchronously via blob.arrayBuffer(). For binary streams this copied every chunk twice, allocated an intermediate copy, and queued a microtask per chunk. Add a fast path that concatenates chunks directly into a single ArrayBuffer when all chunks are non-resizable ArrayBuffer-backed Uint8Arrays (including Buffers) within kMaxLength, falling back to Blob for all other chunk types. Behavior is unchanged. Signed-off-by: Yaroslav Chuhai --- benchmark/streams/consumers.js | 37 ++++++++++++ lib/stream/consumers.js | 63 +++++++++++++++++++- test/parallel/test-stream-consumers.js | 81 ++++++++++++++++++++++++++ 3 files changed, 179 insertions(+), 2 deletions(-) create mode 100644 benchmark/streams/consumers.js diff --git a/benchmark/streams/consumers.js b/benchmark/streams/consumers.js new file mode 100644 index 000000000000..b8557d18e9a4 --- /dev/null +++ b/benchmark/streams/consumers.js @@ -0,0 +1,37 @@ +'use strict'; + +const common = require('../common.js'); +const { Readable } = require('node:stream'); +const consumers = require('node:stream/consumers'); + +const bench = common.createBenchmark(main, { + method: ['arrayBuffer', 'buffer', 'bytes', 'blob'], + type: ['buffer', 'string'], + chunks: [4, 32], + n: [2e3], +}); + +async function main({ n, method, type, chunks }) { + const consume = consumers[method]; + const chunk = type === 'buffer' ? + Buffer.alloc(1024, 65) : + 'a'.repeat(1024); + const data = Array.from({ length: chunks }, () => chunk); + + // Warmup + for (let i = 0; i < 100; i++) { + await consume(Readable.from(data)); + } + + let total = 0; + bench.start(); + for (let i = 0; i < n; i++) { + const res = await consume(Readable.from(data)); + total += res.byteLength ?? res.size; + } + bench.end(n); + + if (total === 0) { + throw new Error('Unexpected empty result'); + } +} diff --git a/lib/stream/consumers.js b/lib/stream/consumers.js index a0d4a5d541ad..09bd692bc17c 100644 --- a/lib/stream/consumers.js +++ b/lib/stream/consumers.js @@ -1,10 +1,26 @@ 'use strict'; const { + ArrayBuffer, + ArrayBufferPrototypeGetResizable, JSONParse, + TypedArrayPrototypeGetBuffer, + TypedArrayPrototypeGetByteLength, + TypedArrayPrototypeSet, Uint8Array, } = primordials; +const { + createUnsafeArrayBuffer, + kMaxLength, +} = internalBinding('buffer'); + +const assert = require('internal/assert'); + +const { + ERR_BUFFER_TOO_LARGE, +} = require('internal/errors').codes; + const { TextDecoder, } = require('internal/encoding'); @@ -13,6 +29,11 @@ const { Blob, } = require('internal/blob'); +const { + isArrayBuffer, + isUint8Array, +} = require('internal/util/types'); + const { Buffer, } = require('buffer'); @@ -34,13 +55,51 @@ async function blob(stream) { return new Blob(chunks); } +/** + * @param {any[]} chunks + * @returns {ArrayBuffer | null} + */ +function concatUint8Arrays(chunks) { + let totalLength = 0; + for (let i = 0; i < chunks.length; i++) { + const chunk = chunks[i]; + if (!isUint8Array(chunk)) + return null; + const backing = TypedArrayPrototypeGetBuffer(chunk); + if (!isArrayBuffer(backing) || ArrayBufferPrototypeGetResizable(backing)) + return null; + totalLength += TypedArrayPrototypeGetByteLength(chunk); + } + + if (totalLength === 0) + return new ArrayBuffer(0); + if (totalLength > kMaxLength) + throw new ERR_BUFFER_TOO_LARGE(kMaxLength); + + const result = createUnsafeArrayBuffer(totalLength); + const view = new Uint8Array(result); + let offset = 0; + for (let i = 0; i < chunks.length; i++) { + const chunk = chunks[i]; + const byteLength = TypedArrayPrototypeGetByteLength(chunk); + if (byteLength !== 0) { + TypedArrayPrototypeSet(view, chunk, offset); + offset += byteLength; + } + } + assert(offset === totalLength); + return result; +} + /** * @param {AsyncIterable|ReadableStream|Readable} stream * @returns {Promise} */ async function arrayBuffer(stream) { - const ret = await blob(stream); - return ret.arrayBuffer(); + const chunks = []; + for await (const chunk of stream) + chunks[chunks.length] = chunk; + return concatUint8Arrays(chunks) ?? new Blob(chunks).arrayBuffer(); } /** diff --git a/test/parallel/test-stream-consumers.js b/test/parallel/test-stream-consumers.js index a9e9c89dccc8..8e42eab26105 100644 --- a/test/parallel/test-stream-consumers.js +++ b/test/parallel/test-stream-consumers.js @@ -291,3 +291,84 @@ const kArrayBuffer = writer.close(), ]).then(common.mustCall()); } + +{ + arrayBuffer(Readable.from([])).then(common.mustCall((ab) => { + assert(ab instanceof ArrayBuffer); + assert.strictEqual(ab.byteLength, 0); + })); +} + +{ + const a = new Uint8Array([1, 2, 3]); + const b = new Uint8Array([4, 5]); + arrayBuffer(Readable.from([a, new Uint8Array(0), b])).then(common.mustCall((ab) => { + a.fill(0); + b.fill(0); + assert.deepStrictEqual(new Uint8Array(ab), new Uint8Array([1, 2, 3, 4, 5])); + })); +} + +{ + const detached = new ArrayBuffer(4); + const detachedView = new Uint8Array(detached); + detachedView.set([9, 8, 7, 6]); + detached.transfer(); + arrayBuffer(Readable.from([new Uint8Array([1, 2]), detachedView, new Uint8Array([3])])) + .then(common.mustCall((ab) => { + assert.deepStrictEqual(new Uint8Array(ab), new Uint8Array([1, 2, 3])); + })); +} + +{ + const resizable = new ArrayBuffer(4, { maxByteLength: 16 }); + assert.rejects( + arrayBuffer(Readable.from([Buffer.from('a'), new Uint8Array(resizable)])), + { + name: 'TypeError', + code: 'ERR_INVALID_ARG_TYPE', + message: /resizable ArrayBuffer/, + }, + ).then(common.mustCall()); +} + +{ + const sab = new SharedArrayBuffer(4); + assert.rejects( + arrayBuffer(Readable.from([Buffer.from('a'), new Uint8Array(sab)])), + { + name: 'TypeError', + code: 'ERR_INVALID_ARG_TYPE', + message: /SharedArrayBuffer/, + }, + ).then(common.mustCall()); +} + +{ + buffer(Readable.from([Buffer.from('hello '), 'world'])).then(common.mustCall((buf) => { + assert.strictEqual(buf.toString(), 'hello world'); + })); +} + +{ + const u16 = new Uint16Array([0x0201]); + const dvBuf = new ArrayBuffer(4); + new Uint8Array(dvBuf).set([10, 20, 30, 40]); + const rawAb = new Uint8Array([50, 60]).buffer; + const clamped = new Uint8ClampedArray([70, 80]); + const mixed = [ + Buffer.from([0]), + u16, + new DataView(dvBuf, 1, 2), + rawAb, + clamped, + ]; + const expected = Buffer.concat([ + Buffer.from([0]), + Buffer.from(u16.buffer, u16.byteOffset, u16.byteLength), + Buffer.from([20, 30, 50, 60, 70, 80]), + ]); + buffer(Readable.from(mixed)).then(common.mustCall((buf) => { + assert.deepStrictEqual(buf, expected); + })); +}