What's the difference between dict() and {}?

前端 未结 8 503
陌清茗
陌清茗 2020-12-12 13:53

So let\'s say I wanna make a dictionary. We\'ll call it d. But there are multiple ways to initialize a dictionary in Python! For example, I could do this:

8条回答
  •  猫巷女王i
    2020-12-12 14:14

    @Jacob: There is a difference in how the objects are allocated, but they are not copy-on-write. Python allocates a fixed-size "free list" where it can quickly allocate dictionary objects (until it fills). Dictionaries allocated via the {} syntax (or a C call to PyDict_New) can come from this free list. When the dictionary is no longer referenced it gets returned to the free list and that memory block can be reused (though the fields are reset first).

    This first dictionary gets immediately returned to the free list, and the next will reuse its memory space:

    >>> id({})
    340160
    >>> id({1: 2})
    340160
    

    If you keep a reference, the next dictionary will come from the next free slot:

    >>> x = {}
    >>> id(x)
    340160
    >>> id({})
    340016
    

    But we can delete the reference to that dictionary and free its slot again:

    >>> del x
    >>> id({})
    340160
    

    Since the {} syntax is handled in byte-code it can use this optimization mentioned above. On the other hand dict() is handled like a regular class constructor and Python uses the generic memory allocator, which does not follow an easily predictable pattern like the free list above.

    Also, looking at compile.c from Python 2.6, with the {} syntax it seems to pre-size the hashtable based on the number of items it's storing which is known at parse time.

提交回复
热议问题