Reputation: 650
What is happening under the hood to have a dict size of 72 bytes (according to getsizeof(dict) after calling .clear() on the dictionary, when a freshly instantiated one returns 240 bytes?
I know a simple dict has a starting size of '8' and resizes itself upon ~66% fullness, is this relatable to the size after calling clear?
I am studying dictionaries and found this quite interesting, what is actually happening?
>>> from sys import getsizeof
>>> dict = {}
>>> getsizeof(dict)
240
>>> dict.clear()
>>> getsizeof(dict)
72
>>>
Upvotes: 2
Views: 98
Reputation: 16485
Assuming we are talking CPython, your intuition is correct. When creating a new dictionary, a keyspace is allocated in dict_new
of size PyDict_MINSIZE. This consumes memory. When calling .clear()
, the keyspace is re-wired to a statically allocated empty key-space, making the dictionary truly empty.
Upvotes: 2