On my machine, the execution speed between d.clear() and d={} is over 100ns so am curious why one would use one over the other.
import timeit
def timing():
d = dict()
if __name__=='__main__':
t = timeit.Timer('timing()', 'from __main__ import timing')
print t.repeat()
d={}creates a new dictionary.d.clear()clears the dictionary.If you use
d={}, then anything pointing todwill be pointing to the oldd. This may introduce a bug.If you use
d.clear(), then anything pointing atdwill now point at the cleared dictionary, this may also introduce a bug, if that was not what you intended.Also, I don’t think
d.clear()will (in CPython) free up memory taken up byd. For performance, CPython doesn’t take the memory away from dictionaries when you delete elements, as the usual use for dictionaries is building a big dictionary, and maybe pruning out a few elements. Reassigning memory (and making sure the hash table stays consistent) would take too long in most use cases. Instead, it fills the dictionary withturds(that’s the technical term on the mailing list), which indicate that an element used to be there but since got deleted. I’m not entirely sure ifd.clear()does this though, but deleting all the keys one by one certainly does.