Currently I'm using async for _ in asyncgen(): pass
I'm looking for "fast route" implementation, approach for sync generators would be:
deque(maxlen=0).extend(generator)
Currently I'm using async for _ in asyncgen(): pass
I'm looking for "fast route" implementation, approach for sync generators would be:
deque(maxlen=0).extend(generator)
Not an answer to your question:
When it comes to plain generators, deque
seems to be just slightly faster than for-loop (over 10%). One can argue that using deque
won't bring any practical advantage and doesn't worth its unreliability and possible side effects.
But it becomes much more important when we talk about asynchronous programming. Word async
tells us that there's some I/O happens inside this async generator: otherwise there was no reason to make this generator asynchronous in the first place. This I/O probably takes over 99% of execution time (see this answer and especially last code snippet there). It'll transform 10% of fast iterating advantage to something completely miserable.
We just won't see any measurable difference between async for loop and alternative approach after all efforts put into optimization.
Generally speaking, "premature optimization is the root of all evil" and only "3% of critical code" is worth optimizing. Which 3% can only be said after measurements and when it comes to asynchronous programming it'll probably be I/O stuff, not iterating.
An answer to your question:
deque
works faster than for loop only because it's implemented in C. There's no (known to me) C implementation of similar functions that work with async iterables. Thus I'm afraid async for _ in asyncgen(): pass
is only option you have right now if you don't want to write C code.