Commit a8faad05dfe for nodejs
commit a8faad05dfebd7570a84a2f90f73e1048dd78a99
Author: James M Snell <jasnell@gmail.com>
Date: Wed Oct 7 14:51:48 2026 +0000
stream: create the stream/iter share() read reaction once per consumer
share()'s #readAfterPull() created each consumer's afterPull() reaction
lazily with `state.afterPull ??= () => {...}`. Because the arrow
function captures `this` and `state`, V8 allocates its context on every
call of #readAfterPull(), even when afterPull() already exists: about 65
bytes per read that waits for the source.
afterPull() is now created by #createAfterPull(), so the context is only
allocated when it is.
share() fan-out, async source, two consumers, 16-byte chunks: 2065 ->
1944 bytes allocated per chunk.
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>
diff --git a/lib/internal/streams/iter/share.js b/lib/internal/streams/iter/share.js
index 2c593fb04c7..0b09a95b1b4 100644
--- a/lib/internal/streams/iter/share.js
+++ b/lib/internal/streams/iter/share.js
@@ -408,7 +408,15 @@ class ShareImpl {
// longer pending: clear it from pendingNext, unless a next() has been
// queued behind it, without a reaction of its own.
#readAfterPull(state) {
- state.afterPull ??= () => {
+ // afterPull() is created by a method of its own: if it were created
+ // here, V8 would allocate the context it captures on every call, even
+ // when it already exists.
+ state.afterPull ??= this.#createAfterPull(state);
+ return PromisePrototypeThen(this.#pullFromSource(false), state.afterPull);
+ }
+
+ #createAfterPull(state) {
+ return () => {
let result;
try {
result = this.#tryRead(state);
@@ -426,7 +434,6 @@ class ShareImpl {
this.#clearWaitingRead(state);
return result;
};
- return PromisePrototypeThen(this.#pullFromSource(false), state.afterPull);
}
#clearWaitingRead(state) {