19/40
Part 5 of 8 · Merging and schedulingLearn and do

The merge wins on streams and on the first few items, not on a full merge in memory

The bug in merge_sorted was a tie. Two fronts with equal values made Python compare the next field, two iterators, and iterators can't be compared. The fix puts the stream number in the middle, (value, i, it), so i settles every tie, as the count did in the job queue.

heapq.merge is the library version, and its docs say it doesn't pull the data into memory all at once. It takes each stream as its own argument, so a list of streams goes in as heapq.merge(*streams): the * unpacks the list, and heapq.merge(*[a, b]) is heapq.merge(a, b).

When everything already fits in memory, the merge isn't faster. On 100 sorted lists of 10,000 integers each:

Predict

100 sorted lists of 10,000 integers. Which is faster for the full merge: sorted(chain(...)) or heapq.merge?

Pick an answer above to see the rest