Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

differences between "d.clear()" and "d={}"

Tags:

python

timing

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()
like image 816
tshepang Avatar asked Nov 28 '22 04:11

tshepang


2 Answers

The difference is that d = {} creates a new dictionary and d.clear() just empties the dictionary you already have. This subtle difference matters if you have other places in your code holding references to your dictionary. In the first case those other objects won't see any change because you haven't modified the original dictionary. The following code shows this difference in action.

Creating a new dictionary:

>>> d = {'foo': 'bar'}
>>> d2 = d
>>> d = {}
>>> d2
{'foo': 'bar'}

Clearing the existing dictionary:

>>> d = {'foo': 'bar'}
>>> d2 = d
>>> d.clear()
>>> d2
{}
like image 115
Mark Byers Avatar answered Nov 30 '22 18:11

Mark Byers


d={} creates a new dictionary.

d.clear() clears the dictionary.

If you use d={}, then anything pointing to d will be pointing to the old d. This may introduce a bug.

If you use d.clear(), then anything pointing at d will 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 by d. 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 with turds (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 if d.clear() does this though, but deleting all the keys one by one certainly does.

like image 44
wisty Avatar answered Nov 30 '22 18:11

wisty