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

Skip to content

Commit f276232

Browse files
committed
Issue #18962: Optimize the single iterator case for heapq.merge()
Suggested by Wouter Bolsterlee.
1 parent aa1004d commit f276232

2 files changed

Lines changed: 10 additions & 5 deletions

File tree

Lib/heapq.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,7 @@ def merge(*iterables):
358358
359359
'''
360360
_heappop, _heapreplace, _StopIteration = heappop, heapreplace, StopIteration
361+
_len = len
361362

362363
h = []
363364
h_append = h.append
@@ -369,17 +370,20 @@ def merge(*iterables):
369370
pass
370371
heapify(h)
371372

372-
while 1:
373+
while _len(h) > 1:
373374
try:
374-
while 1:
375-
v, itnum, next = s = h[0] # raises IndexError when h is empty
375+
while True:
376+
v, itnum, next = s = h[0]
376377
yield v
377378
s[0] = next() # raises StopIteration when exhausted
378379
_heapreplace(h, s) # restore heap condition
379380
except _StopIteration:
380381
_heappop(h) # remove empty iterator
381-
except IndexError:
382-
return
382+
if h:
383+
# fast case when only a single iterator remains
384+
v, itnum, next = h[0]
385+
yield v
386+
yield from next.__self__
383387

384388
# Extend the implementations of nsmallest and nlargest to use a key= argument
385389
_nsmallest = nsmallest

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@ Paul Boddie
135135
Matthew Boedicker
136136
Robin Boerdijk
137137
David Bolen
138+
Wouter Bolsterlee
138139
Gawain Bolton
139140
Forest Bond
140141
Gregory Bond

0 commit comments

Comments
 (0)