Commit f2762321 authored by Raymond Hettinger's avatar Raymond Hettinger

Issue #18962: Optimize the single iterator case for heapq.merge()

Suggested by Wouter Bolsterlee.
parent aa1004da
...@@ -358,6 +358,7 @@ def merge(*iterables): ...@@ -358,6 +358,7 @@ def merge(*iterables):
''' '''
_heappop, _heapreplace, _StopIteration = heappop, heapreplace, StopIteration _heappop, _heapreplace, _StopIteration = heappop, heapreplace, StopIteration
_len = len
h = [] h = []
h_append = h.append h_append = h.append
...@@ -369,17 +370,20 @@ def merge(*iterables): ...@@ -369,17 +370,20 @@ def merge(*iterables):
pass pass
heapify(h) heapify(h)
while 1: while _len(h) > 1:
try: try:
while 1: while True:
v, itnum, next = s = h[0] # raises IndexError when h is empty v, itnum, next = s = h[0]
yield v yield v
s[0] = next() # raises StopIteration when exhausted s[0] = next() # raises StopIteration when exhausted
_heapreplace(h, s) # restore heap condition _heapreplace(h, s) # restore heap condition
except _StopIteration: except _StopIteration:
_heappop(h) # remove empty iterator _heappop(h) # remove empty iterator
except IndexError: if h:
return # fast case when only a single iterator remains
v, itnum, next = h[0]
yield v
yield from next.__self__
# Extend the implementations of nsmallest and nlargest to use a key= argument # Extend the implementations of nsmallest and nlargest to use a key= argument
_nsmallest = nsmallest _nsmallest = nsmallest
......
...@@ -135,6 +135,7 @@ Paul Boddie ...@@ -135,6 +135,7 @@ Paul Boddie
Matthew Boedicker Matthew Boedicker
Robin Boerdijk Robin Boerdijk
David Bolen David Bolen
Wouter Bolsterlee
Gawain Bolton Gawain Bolton
Forest Bond Forest Bond
Gregory Bond Gregory Bond
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment