[Python-ideas] A key parameter for heapq.merge

Steven D'Aprano steve at pearwood.info
Mon Jan 9 00:46:48 CET 2012


Simon Sapin wrote:

> I’m working on a patch for a key parameter. I think it can be pretty 
> straightforward, but I’ll measure if the "no key" case becomes slower 
> (calls to lambda x: x) At worst we can always duplicate the loop.

In my experience, it is *much* faster to test against None every time through 
the loop than to call a do-nothing function. Instead of this:

if key is None:
     key = lambda x: x
for value in heap:
     do_something_with(key(value))

this is much faster:

for value in heap:
     if key is None:
         do_something_with(value)
     else:
         do_something_with(key(value))

and this is faster still:

if key is None:
     for value in heap:
         do_something_with(value)
else:
     for value in heap:
         do_something_with(key(value))

YMMV; I encourage you to benchmark.




-- 
Steven




More information about the Python-ideas mailing list