stream: snapshot common stream/iter byte views in fewer fields

To detect that a chunk accepted by a writer was resized or detached
before it is read, a ByteViewSnapshot of its buffer, byteLength,
byteOffset and detached state is taken for every chunk written, and
checked when it is read.

A non-empty view of a fixed-length, non-shared ArrayBuffer can only
change by the buffer being detached, which makes its byteLength 0, as
recordChunk() already relies on. Snapshot such views, the common case,
as a FixedByteView of the view and its byteLength, which is all that
needs to be checked.

Writing 16-byte chunks to a push() stream and reading them is about 17%
faster with await write() and 37% faster with writeSync(), and piping
them about 29% and 51%; 64 KiB chunks are about 7-13% faster.

Assisted-by: OpenCode
Signed-off-by: James M Snell <jasnell@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/66504
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
This commit is contained in:
James M Snell authored and Antoine du Hamel committed 2026-11-25 18:00:50 +01:00
1 parent dc3360eef3
commit 6a291743b1
1 file changed
+27 -3
+27 -3
View File
@@ -376,6 +376,17 @@ function ByteViewSnapshot(value, buffer, sharedBufferView) {
}
ByteViewSnapshot.prototype = ObjectFreeze({ __proto__: null });
// The snapshot of a non-empty view of a fixed-length, non-shared ArrayBuffer,
// the common case. Such a view can only change by the buffer being detached,
// which makes its byteLength 0, so its byteLength is all that needs to be
// recorded. `buffer` is null to tell it from a ByteViewSnapshot.
function FixedByteView(value, byteLength) {
this.value = value;
this.byteLength = byteLength;
this.buffer = null;
}
FixedByteView.prototype = ObjectFreeze({ __proto__: null });
function BatchEntry(views, byteLength) {
this.views = views;
this.byteLength = byteLength;
@@ -399,12 +410,25 @@ PendingWrite.prototype = ObjectFreeze({ __proto__: null });
function snapshotByteView(value) {
const buffer = TypedArrayPrototypeGetBuffer(value);
const sharedBufferView = isSharedArrayBuffer(buffer) ?
new Uint8Array(buffer) : undefined;
return new ByteViewSnapshot(value, buffer, sharedBufferView);
if (isSharedArrayBuffer(buffer)) {
return new ByteViewSnapshot(value, buffer, new Uint8Array(buffer));
}
const byteLength = TypedArrayPrototypeGetByteLength(value);
if (byteLength !== 0 && !ArrayBufferPrototypeGetResizable(buffer)) {
return new FixedByteView(value, byteLength);
}
return new ByteViewSnapshot(value, buffer, undefined);
}
function validateByteView(snapshot) {
if (snapshot.buffer === null) {
const { value } = snapshot;
if (TypedArrayPrototypeGetByteLength(value) !== snapshot.byteLength) {
throw new ERR_INVALID_STATE.TypeError(
'Byte view was resized or detached after being accepted');
}
return value;
}
const {
value,
buffer,