Skip to content

Commit 43a5b9c

Browse files
jasnelladuh95
authored andcommitted
stream: create stream/iter from() values without async generators
from() of a string, ArrayBuffer, ArrayBufferView or array of Uint8Arrays returns an iterable whose iterators are async generators yielding the value's batches. Creating and resuming an async generator costs a generator object, its frame and several promises, which dominates the cost of a short stream: creating and reading a stream of one 16-byte chunk spent a quarter of its time collecting garbage. Iterate such values with a small iterator that does what the generator did: each iteration starts over and yields the same batches, bounded as before, and return() and throw() end it, throw() rejecting with its argument. Creating and reading a stream of one 16-byte chunk with from() is about 1.8 times faster, with 900 bytes less allocated per stream. 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 eb3a8d2 commit 43a5b9c

2 files changed

Lines changed: 91 additions & 29 deletions

File tree

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

Lines changed: 61 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1335,6 +1335,64 @@ function fromSync(input) {
13351335
};
13361336
}
13371337

1338+
/**
1339+
* An async iterable yielding the chunks of `batch`, a Uint8Array[], in
1340+
* batches of at most FROM_BATCH_SIZE chunks, for from() of values that need
1341+
* no normalization. Each iterator does what an async generator yielding the
1342+
* batches would, without the generator object and the promises and frames
1343+
* of resuming it: next() gives the batches, then done; return() and throw()
1344+
* end the iteration, throw() rejecting with its argument.
1345+
* @param {Uint8Array[]} batch
1346+
* @returns {AsyncIterable<Uint8Array[]>}
1347+
*/
1348+
function createBatchSource(batch) {
1349+
return {
1350+
__proto__: null,
1351+
[SymbolAsyncIterator]() {
1352+
return createBatchIterator(batch);
1353+
},
1354+
[kValidatedSource]: true,
1355+
};
1356+
}
1357+
1358+
function createBatchIterator(batch) {
1359+
let index = 0;
1360+
1361+
// The next batch, or null once done.
1362+
function nextBatch() {
1363+
if (index >= batch.length) {
1364+
index = batch.length;
1365+
return null;
1366+
}
1367+
if (index === 0 && batch.length <= FROM_BATCH_SIZE) {
1368+
index = batch.length;
1369+
return batch;
1370+
}
1371+
const start = index;
1372+
index += FROM_BATCH_SIZE;
1373+
return ArrayPrototypeSlice(batch, start, index);
1374+
}
1375+
1376+
return ObjectSetPrototypeOf({
1377+
next() {
1378+
const value = nextBatch();
1379+
return PromiseResolve(value === null ?
1380+
new IterResult(true, undefined) : new IterResult(false, value));
1381+
},
1382+
return(value) {
1383+
index = batch.length;
1384+
return PromiseResolve(new IterResult(true, value));
1385+
},
1386+
throw(error) {
1387+
index = batch.length;
1388+
return PromiseReject(error);
1389+
},
1390+
[SymbolAsyncIterator]() {
1391+
return this;
1392+
},
1393+
}, null);
1394+
}
1395+
13381396
/**
13391397
* Create a ByteStreamReadable from a ByteInput or Streamable.
13401398
* @param {string|ArrayBuffer|ArrayBufferView|Iterable|AsyncIterable} input
@@ -1347,14 +1405,7 @@ function from(input) {
13471405

13481406
// Check for primitives first (ByteInput)
13491407
if (isPrimitiveChunk(input)) {
1350-
const chunk = primitiveToUint8Array(input);
1351-
return {
1352-
__proto__: null,
1353-
async *[SymbolAsyncIterator]() {
1354-
yield [chunk];
1355-
},
1356-
[kValidatedSource]: true,
1357-
};
1408+
return createBatchSource([primitiveToUint8Array(input)]);
13581409
}
13591410

13601411
// Check toAsyncStreamable protocol (takes precedence over toStreamable and
@@ -1392,31 +1443,12 @@ function from(input) {
13921443
// the throughput benefit of batched processing.
13931444
if (ArrayIsArray(input)) {
13941445
if (input.length === 0) {
1395-
return {
1396-
__proto__: null,
1397-
async *[SymbolAsyncIterator]() {
1398-
// Empty - yield nothing
1399-
},
1400-
[kValidatedSource]: true,
1401-
};
1446+
return createBatchSource(input);
14021447
}
14031448
if (isUint8Array(input[0])) {
14041449
const allUint8 = ArrayPrototypeEvery(input, isUint8Array);
14051450
if (allUint8) {
1406-
const batch = input;
1407-
return {
1408-
__proto__: null,
1409-
async *[SymbolAsyncIterator]() {
1410-
if (batch.length <= FROM_BATCH_SIZE) {
1411-
yield batch;
1412-
} else {
1413-
for (let i = 0; i < batch.length; i += FROM_BATCH_SIZE) {
1414-
yield ArrayPrototypeSlice(batch, i, i + FROM_BATCH_SIZE);
1415-
}
1416-
}
1417-
},
1418-
[kValidatedSource]: true,
1419-
};
1451+
return createBatchSource(input);
14201452
}
14211453
}
14221454
}

‎test/parallel/test-stream-iter-from-async.js‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -828,7 +828,37 @@ async function testFromReturnsItsOwnResults() {
828828
}
829829
}
830830

831+
// from() of a value needing no normalization reads like an async generator
832+
// yielding its batches: each iteration starts over, return() and throw()
833+
// end it, and arrays are yielded in bounded batches.
834+
async function testFromValueIteration() {
835+
const chunk = new Uint8Array([1]);
836+
const source = from(chunk);
837+
for (let i = 0; i < 2; i++) {
838+
const batches = await Array.fromAsync(source);
839+
assert.deepStrictEqual(batches, [[chunk]]);
840+
}
841+
842+
let iterator = source[Symbol.asyncIterator]();
843+
assert.deepStrictEqual({ ...await iterator.return(5) },
844+
{ done: true, value: 5 });
845+
assert.strictEqual((await iterator.next()).done, true);
846+
847+
iterator = source[Symbol.asyncIterator]();
848+
assert.deepStrictEqual((await iterator.next()).value, [chunk]);
849+
const error = new Error('thrown');
850+
await assert.rejects(iterator.throw(error), error);
851+
assert.strictEqual((await iterator.next()).done, true);
852+
853+
const chunks = Array.from({ length: 300 }, () => chunk);
854+
const lengths = (await Array.fromAsync(from(chunks)))
855+
.map((batch) => batch.length);
856+
assert.deepStrictEqual(lengths, [128, 128, 44]);
857+
assert.deepStrictEqual(await Array.fromAsync(from([])), []);
858+
}
859+
831860
Promise.all([
861+
testFromValueIteration(),
832862
testFromReturnsItsOwnResults(),
833863
testFromString(),
834864
testFromAsyncGenerator(),

0 commit comments

Comments
 (0)