Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b3e479a

Browse files
committed
gh-NNNN: Skip creating GatheringFuture if all futures finished eagerly
1 parent da1980a commit b3e479a

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

Lib/asyncio/tasks.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -815,6 +815,7 @@ def _done_callback(fut):
815815
nfinished = 0
816816
loop = None
817817
outer = None # bpo-46672
818+
all_finished = True
818819
for arg in coros_or_futures:
819820
if arg not in arg_to_fut:
820821
fut = ensure_future(arg, loop=loop)
@@ -829,15 +830,26 @@ def _done_callback(fut):
829830

830831
nfuts += 1
831832
arg_to_fut[arg] = fut
832-
fut.add_done_callback(_done_callback)
833+
if fut.done():
834+
# call the callback immediately instead of scheduling it
835+
_done_callback(fut)
836+
else:
837+
all_finished = False
838+
fut.add_done_callback(_done_callback)
833839

834840
else:
835841
# There's a duplicate Future object in coros_or_futures.
836842
fut = arg_to_fut[arg]
837843

838844
children.append(fut)
839845

840-
outer = _GatheringFuture(children, loop=loop)
846+
if all_finished:
847+
# optimization: skip creating GatheringFuture if all children completed
848+
# (e.g. when all coros are able to complete eagerly)
849+
outer = futures.Future(loop=loop)
850+
outer.set_result([c.result for c in children])
851+
else:
852+
outer = _GatheringFuture(children, loop=loop)
841853
return outer
842854

843855

0 commit comments

Comments
 (0)