Is there a significant difference in functionality and/or efficiency between using heappushpop and peeking at the heap first then deciding whether to pop (using heapreplace)?
E.g.
from heapq import *
a = [5, 18, 9, 14, 22]
heapify(a) # a = [5, 14, 9, 18, 22]
heappushpop(a, 7) # Returns 5 and a = [7, 14, 9, 18, 22]
heappushpop(a, 2) # Returns 2 and a = [7, 14, 9, 18, 22]
from heapq import *
def customPop(heap, val):
if heap and heap[0] >= val:
return val
return heapreplace(heap, val)
a = [5, 18, 9, 14, 22]
heapify(a) # a = [5, 14, 9, 18, 22]
customPop(a, 7) # Returns 5 and a = [7, 14, 9, 18, 22]
customPop(a, 2) # Returns 2 and a = [7, 14, 9, 18, 22]
The custom method appears to be about 1.5 times slower.
Benchmarked with ipython and python 3.10.3 with:
%%timeitheappushpop(a, 7)heappushpop(a, 2)customPop(a, 7)customPop(a, 2)