I was curious about this as well and did a timeit
test and it seems there's no difference at all (see the results here). Essentially, the best timings of 5 runs each of discard
and remove
were compared. This was repeated 3 times and remove
was slower than discard
once and discard
was slower twice.
The code used for the experiment is as follows.
import timeit
from collections import Counter
setup = 'set_, keys = set(range(1000000)), iter(range(1000000))'
lst = []
for _ in range(3):
t1 = timeit.repeat('set_.discard(next(keys))', setup)
t2 = timeit.repeat('set_.remove(next(keys))', setup)
lst.append(min(t1) < min(t2))
print("In 3 experiments, remove was slower than discard {} times".format(Counter(lst)[True]))
# In 3 experiments, remove was slower than discard 1 times