Skip to content

Commit 90b592d

Browse files
jasnelladuh95
authored andcommitted
stream: do not keep stream/iter from() sync sources busy for a tick
The iterator of from() over a sync iterable stayed busy until the microtask after every result it produced synchronously, as an async generator stays busy until the tick after a yield, so that a call made synchronously after one was queued behind it. That cost a microtask per batch, also when nothing was ever queued. Settle each operation when its result is known instead, as the normalizer of async sources does: a call made after one that finished synchronously now runs at once, and calls queued while one was in progress, such as behind a value normalized asynchronously, still run a microtask later. Only calls made back to back without awaiting are affected: a second next() reads the source during the call, and a return() made after it no longer cancels it, as it did when it was still queued. The other iterators of from(), for values and async sources, already behaved this way. The queue's release() is no longer used. Iterating from() over a sync source yielding one-chunk batches is about 1.38 times faster, now on par with a ReadableStream, and with 64-chunk batches about 7% 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 e2fccac commit 90b592d

3 files changed

Lines changed: 50 additions & 28 deletions

File tree

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

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1323,19 +1323,15 @@ function createSyncSourceNormalizer(source, context) {
13231323
let done = false;
13241324
// A normalizeAsyncSourceValue() generator for the value being normalized.
13251325
let valueBatches = null;
1326-
const { run, settled, release, idle } = createOperationQueue();
1327-
1328-
// Results are often produced synchronously. An async generator stays busy
1329-
// until the tick after a yield or return (both await their operand), so
1330-
// that a next(), return() or throw() made synchronously after this one is
1331-
// queued behind it; do the same.
1332-
// TODO(@jasnell): This costs a microtask per batch. Running a call made
1333-
// while the previous one has finished synchronously right away would make
1334-
// for-await over from(syncSource) about 1.3x faster, at the cost of this
1335-
// async generator parity for calls made back to back without awaiting
1336-
// (see testFromSyncSourceQueuesBehindReturn).
1326+
const { run, settled, idle } = createOperationQueue();
1327+
1328+
// Results are often produced synchronously. Once one is, the next call
1329+
// runs at once, as for the async source normalizer; calls queued while
1330+
// an operation was in progress run a microtask later. (An async generator
1331+
// would stay busy until the tick after a yield, and queue a call made
1332+
// synchronously after one: that costs a microtask per batch.)
13371333
function finish(result) {
1338-
PromisePrototypeThen(kResolvedPromise, release);
1334+
settled();
13391335
return result;
13401336
}
13411337

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

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -604,7 +604,7 @@ class QueuedOperation {
604604
* Serializes the operations of a hand-written async iterator the way an
605605
* async generator queues its requests: an operation started while another
606606
* is in progress waits until it has settled.
607-
* @returns {{ run: Function, settled: Function, release: Function }}
607+
* @returns {{ run: Function, settled: Function, idle: Function }}
608608
*/
609609
function createOperationQueue() {
610610
let busy = false;
@@ -639,12 +639,6 @@ function createOperationQueue() {
639639
PromisePrototypeThen(kResolvedPromise, drain);
640640
}
641641
},
642-
// Like settled(), but start the next queued operation now, as an async
643-
// generator does once the await of a yield or return completes.
644-
release() {
645-
busy = false;
646-
drain();
647-
},
648642
// Whether no operation is running or queued.
649643
idle() {
650644
return !busy && (queue === null || queue.length === 0);

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

Lines changed: 41 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -856,20 +856,52 @@ async function testFromSyncSourceReturnAndThrow() {
856856
}
857857
}
858858

859-
async function testFromSyncSourceQueuesBehindReturn() {
860-
// A next() made synchronously after another waits for it, and so sees a
861-
// return() made synchronously after it as well.
862-
const log = [];
863-
const iterator = from(createLoggedSyncSource(log, [
859+
async function testFromSyncSourceCallOrder() {
860+
// A next() made synchronously after another that finished synchronously
861+
// runs at once, before a return() made after it.
862+
let log = [];
863+
let iterator = from(createLoggedSyncSource(log, [
864864
[Uint8Array.of(1)], 'a', [Uint8Array.of(2)],
865865
]))[Symbol.asyncIterator]();
866-
const results = [iterator.next(), iterator.next(), iterator.return()];
866+
let results = [iterator.next(), iterator.next(), iterator.return()];
867+
for (let i = 0; i < results.length; i++) {
868+
await settle(log, `result ${i}`, results[i]);
869+
}
870+
assert.deepStrictEqual(log, [
871+
'iterator', 'next 0', 'next 1', 'result 0: 1', 'result 1: 1', 'return',
872+
'result 2: done',
873+
]);
874+
875+
// A call made while a value is normalized asynchronously is queued
876+
// behind it, and so a return() made then cancels it.
877+
log = [];
878+
iterator = from(createLoggedSyncSource(log, [
879+
[Uint8Array.of(1)], Promise.resolve(Uint8Array.of(2)), [Uint8Array.of(3)],
880+
]))[Symbol.asyncIterator]();
881+
results = [iterator.next(), iterator.next(), iterator.next(),
882+
iterator.return()];
867883
for (let i = 0; i < results.length; i++) {
868884
await settle(log, `result ${i}`, results[i]);
869885
}
870886
assert.deepStrictEqual(log, [
871-
'iterator', 'next 0', 'next 1', 'return', 'result 0: 1',
872-
'result 1: AbortError', 'result 2: done',
887+
'iterator', 'next 0', 'next 1', 'result 0: 1', 'return',
888+
'result 1: AbortError', 'result 2: done', 'result 3: done',
889+
]);
890+
891+
// A next() made synchronously after another reads the source at once.
892+
log = [];
893+
iterator = from(createLoggedSyncSource(log, [
894+
[Uint8Array.of(1)], [Uint8Array.of(2)],
895+
]))[Symbol.asyncIterator]();
896+
const first = iterator.next();
897+
log.push('first called');
898+
const second = iterator.next();
899+
log.push('second called');
900+
await settle(log, 'first', first);
901+
await settle(log, 'second', second);
902+
assert.deepStrictEqual(log, [
903+
'iterator', 'next 0', 'first called', 'next 1', 'second called',
904+
'first: 1', 'second: 1',
873905
]);
874906
}
875907

@@ -975,5 +1007,5 @@ Promise.all([
9751007
testFromSyncSourceLargeAndEmptyBatches(),
9761008
testFromSyncSourceErrors(),
9771009
testFromSyncSourceReturnAndThrow(),
978-
testFromSyncSourceQueuesBehindReturn(),
1010+
testFromSyncSourceCallOrder(),
9791011
]).then(common.mustCall());

0 commit comments

Comments
 (0)