Skip to content

Commit a9ad2cd

Browse files
jasnelladuh95
authored andcommitted
stream: encode small stream/iter strings into a pool
stream/iter encoded every string written, yielded or piped with TextEncoder.encode(), into an ArrayBuffer of its own. Writing many small strings, as a server-side renderer does, was then mostly the cost of allocating them. Encode strings whose UTF-8 encoding certainly fits in 8 KiB into a 64 KiB pool, as Buffer.from() does, with the fast API utf8WriteStatic(), and pass on views of it. The pool is untransferable, so that transferring the buffer of one chunk cannot detach the others. For SSR-like strings of about 65 bytes, writing to a push() stream with writeSync() is about 4 times faster, and with await write() about 2.2 times faster. Assisted-by: OpenCode Signed-off-by: James M Snell <jasnell@gmail.com> PR-URL: #66504 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
1 parent 201cbb2 commit a9ad2cd

3 files changed

Lines changed: 69 additions & 2 deletions

File tree

‎doc/api/stream_iter.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,10 @@ are automatically UTF-8 encoded when passed to `from()`, `push()`, or
9494
`pipeTo()`. This removes ambiguity around encodings and enables zero-copy
9595
transfers between streams and native code.
9696

97+
Like [`Buffer.from()`][] for strings, small strings are encoded into a shared
98+
pool: the resulting {Uint8Array} is a view of a larger {ArrayBuffer}, which
99+
cannot be transferred.
100+
97101
### Batching
98102

99103
Each iteration yields a **batch** -- an {Array} of {Uint8Array} chunks
@@ -2413,6 +2417,7 @@ console.log(textSync(stream)); // 'hello world'
24132417
[Iterable Streams API]: https://iter-streams.proposal.wintertc.org/
24142418
[`--experimental-stream-iter`]: cli.md#--experimental-stream-iter
24152419
[`Broadcast.from()`]: #broadcastfrominput-options
2420+
[`Buffer.from()`]: buffer.md#static-method-bufferfromstring-encoding
24162421
[`Share.from()`]: #static-method-sharefrominput-options
24172422
[`SyncShare.fromSync()`]: #static-method-syncsharefromsyncinput-options
24182423
[`array()`]: #arraysource-options

‎lib/internal/streams/iter/utils.js‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ const {
2626
} = internalBinding('util');
2727

2828
const { TextEncoder } = require('internal/encoding');
29+
const { markAsUntransferable } = require('internal/buffer');
30+
const { utf8WriteStatic } = internalBinding('buffer');
2931
const {
3032
codes: {
3133
ERR_INVALID_ARG_TYPE,
@@ -63,6 +65,37 @@ const kResolvedPromise = PromiseResolve();
6365
// Shared TextEncoder instance for string conversion.
6466
const encoder = new TextEncoder();
6567

68+
// Small strings are encoded into a pool, like Buffer.from(string), instead
69+
// of each into an ArrayBuffer of its own: writing many small strings, as a
70+
// server-side renderer does, is otherwise mostly the cost of allocating
71+
// them. The pool is untransferable, so that transferring the buffer of one
72+
// chunk cannot detach the others. A string is pooled when its UTF-8 encoding
73+
// fits in kMaxPooledByteLength bytes for certain: every UTF-16 code unit
74+
// encodes to at most 3 bytes.
75+
const kStringPoolSize = 64 * 1024;
76+
const kMaxPooledLength = 8 * 1024 / 3;
77+
let stringPool = null;
78+
let stringPoolBuffer;
79+
let stringPoolOffset = 0;
80+
81+
function encodeString(string) {
82+
const length = string.length;
83+
if (length > kMaxPooledLength) return encoder.encode(string);
84+
const maxByteLength = length * 3;
85+
if (stringPool === null ||
86+
maxByteLength > kStringPoolSize - stringPoolOffset) {
87+
stringPool = new Uint8Array(kStringPoolSize);
88+
stringPoolBuffer = TypedArrayPrototypeGetBuffer(stringPool);
89+
markAsUntransferable(stringPoolBuffer);
90+
stringPoolOffset = 0;
91+
}
92+
const offset = stringPoolOffset;
93+
const written = utf8WriteStatic(stringPool, string, offset, maxByteLength);
94+
// Keep the chunks 8-byte aligned, as Buffer does.
95+
stringPoolOffset = (offset + written + 7) & ~7;
96+
return new Uint8Array(stringPoolBuffer, offset, written);
97+
}
98+
6699
// Default high water marks for push and multi-consumer streams. These values
67100
// are somewhat arbitrary but have been tested across various workloads and
68101
// appear to yield the best overall throughput/latency balance.
@@ -457,7 +490,7 @@ function getMinCursor(consumers, fallback) {
457490
*/
458491
function toUint8Array(chunk) {
459492
if (typeof chunk === 'string') {
460-
return encoder.encode(chunk);
493+
return encodeString(chunk);
461494
}
462495
if (!isUint8Array(chunk)) {
463496
throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Uint8Array'], chunk);

‎test/parallel/test-stream-iter-push-writer.js‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
const common = require('../common');
55
const assert = require('assert');
6-
const { dump, ondrain, push, text } = require('stream/iter');
6+
const { dump, push, ondrain, text, array } = require('stream/iter');
77
const { setImmediate } = require('timers/promises');
88

99
async function testOndrain() {
@@ -663,7 +663,36 @@ async function testFailRejectsPendingReadWithFalsyReason() {
663663
);
664664
}
665665

666+
// Strings are encoded as UTF-8 (lone surrogates as U+FFFD), small ones into
667+
// a shared, untransferable pool, which must not mix up their bytes, also
668+
// when the pool fills up; large ones each into an ArrayBuffer of their own.
669+
async function testWriteStrings() {
670+
const strings = [];
671+
for (let i = 0; i < 3000; i++) {
672+
strings.push(`row ${i} héllo 😀 \ud800 ${'x'.repeat(i % 97)}`);
673+
}
674+
strings.push('y'.repeat(10000), 'z');
675+
const { writer, readable } = push();
676+
const read = array(readable);
677+
for (const string of strings) {
678+
if (!writer.writeSync(string)) await writer.write(string);
679+
}
680+
await writer.end();
681+
const chunks = await read;
682+
const decoder = new TextDecoder();
683+
assert.deepStrictEqual(chunks.map((chunk) => decoder.decode(chunk)),
684+
strings.map((s) => s.replace('\ud800', '\ufffd')));
685+
for (const chunk of chunks) {
686+
assert.strictEqual(Object.getPrototypeOf(chunk), Uint8Array.prototype);
687+
}
688+
const pooled = chunks[0];
689+
assert.ok(pooled.buffer.byteLength > pooled.byteLength);
690+
assert.throws(() => pooled.buffer.transfer(), TypeError);
691+
assert.strictEqual(chunks[3000].buffer.byteLength, 10000);
692+
}
693+
666694
Promise.all([
695+
testWriteStrings(),
667696
testOndrain(),
668697
testDropPoliciesReportPhysicalCapacity(),
669698
testOndrainNonDrainable(),

0 commit comments

Comments
 (0)