summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2013-09-11 06:15:40 (GMT)
committerRaymond Hettinger <python@rcn.com>2013-09-11 06:15:40 (GMT)
commitf27623215cbcb1cc23acfd6d2e2e7b3d5b3f994c (patch)
treeffe91a51005530bad2c38d142a953ec1557919ae
parentaa1004da9797a7e440c98ddaa151153daec9e538 (diff)
downloadcpython-f27623215cbcb1cc23acfd6d2e2e7b3d5b3f994c.zip
cpython-f27623215cbcb1cc23acfd6d2e2e7b3d5b3f994c.tar.gz
cpython-f27623215cbcb1cc23acfd6d2e2e7b3d5b3f994c.tar.bz2
Issue #18962: Optimize the single iterator case for heapq.merge()
Suggested by Wouter Bolsterlee.
-rw-r--r--Lib/heapq.py14
-rw-r--r--Misc/ACKS1
2 files changed, 10 insertions, 5 deletions
diff --git a/Lib/heapq.py b/Lib/heapq.py
index 00b429c..d615239 100644
--- a/Lib/heapq.py
+++ b/Lib/heapq.py
@@ -358,6 +358,7 @@ def merge(*iterables):
'''
_heappop, _heapreplace, _StopIteration = heappop, heapreplace, StopIteration
+ _len = len
h = []
h_append = h.append
@@ -369,17 +370,20 @@ def merge(*iterables):
pass
heapify(h)
- while 1:
+ while _len(h) > 1:
try:
- while 1:
- v, itnum, next = s = h[0] # raises IndexError when h is empty
+ while True:
+ v, itnum, next = s = h[0]
yield v
s[0] = next() # raises StopIteration when exhausted
_heapreplace(h, s) # restore heap condition
except _StopIteration:
_heappop(h) # remove empty iterator
- except IndexError:
- return
+ if h:
+ # 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
_nsmallest = nsmallest
diff --git a/Misc/ACKS b/Misc/ACKS
index 030f980..9d0dc46 100644
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -135,6 +135,7 @@ Paul Boddie
Matthew Boedicker
Robin Boerdijk
David Bolen
+Wouter Bolsterlee
Gawain Bolton
Forest Bond
Gregory Bond