Issue 4790: Eliminate unnecessary work from heapq's nlargest() and nsmallest()
functions for the common case where no key function is specified.
diff --git a/Lib/heapq.py b/Lib/heapq.py
index 0a83b76..c13d650 100644
--- a/Lib/heapq.py
+++ b/Lib/heapq.py
@@ -354,6 +354,10 @@
Equivalent to: sorted(iterable, key=key)[:n]
"""
+ if key is None:
+ it = izip(iterable, count()) # decorate
+ result = _nsmallest(n, it)
+ return map(itemgetter(0), result) # undecorate
in1, in2 = tee(iterable)
it = izip(imap(key, in1), count(), in2) # decorate
result = _nsmallest(n, it)
@@ -365,6 +369,10 @@
Equivalent to: sorted(iterable, key=key, reverse=True)[:n]
"""
+ if key is None:
+ it = izip(iterable, imap(neg, count())) # decorate
+ result = _nlargest(n, it)
+ return map(itemgetter(0), result) # undecorate
in1, in2 = tee(iterable)
it = izip(imap(key, in1), imap(neg, count()), in2) # decorate
result = _nlargest(n, it)