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

On my machine, the execution speed between d.clear() and d={} exceeds 100 ns, so it’s curious why you need to 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() 
+4
source share
2 answers

d={} creates a new dictionary.

d.clear() clears the dictionary.

If you use d={} , then everything that points to d will point to the old d . This may result in an error.

If you use d.clear() , then everything that points to d will now point to a cleared dictionary, this can also lead to an error if this is not what you intended.

Also, I don't think d.clear() will (in CPython) free up the memory occupied by d . For performance, CPython does not retrieve memory from dictionaries when deleting elements, since the usual use of dictionaries leads to the creation of a large dictionary and possibly to the reduction of several elements. Reassigning the memory (and ensuring that the hash table remains consistent) will take too much time in most use cases. Instead, it fills in the turds dictionary (this is a technical term on the mailing list), which indicates that the item has been there, but since it was deleted. I'm not quite sure if d.clear() does this, although of course it deletes all the keys one by one.

+6
source

The difference is that d = {} creates a new dictionary, and d.clear() just frees the dictionary that you already have. This subtle difference matters if you have other places in your code that contain links to your dictionary. In the first case, these other objects will not see any changes, because you have not changed the original dictionary. The following code shows this difference in action.

Create a new dictionary:

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

Delete an existing dictionary:

 >>> d = {'foo': 'bar'} >>> d2 = d >>> d.clear() >>> d2 {} 
+19
source

Source: https://habr.com/ru/post/1308281/


All Articles