代码之家  ›  专栏  ›  技术社区  ›  Dimitris Fasarakis Hilliard

为什么字典在删除后不调整大小?

  •  7
  • Dimitris Fasarakis Hilliard  · 技术社区  · 7 年前

    显然,删除字典中的条目不会触发任何大小调整。只有在添加条目后才会触发调整大小。

    这可以从以下方面看出:

    # Drastic example, nobody does such 
    # things with dicts FWIK
    from sys import getsizeof
    
    d = {i:i for i in range(100)}
    print(getsizeof(d))  # 4704
    for i in range(100):
        del d[i]  # similarly with pop
    print(getsizeof(d))  # 4704
    d[0] = 1 # triggers resize
    

    a question on SO (根据我的发现)。 set s的行为方式类似,这与dicts的行为一致。

    list list_resize comment :

    /* Bypass realloc() when a previous overallocation is large enough
       to accommodate the newsize.  If the newsize falls lower than half
       the allocated size, then proceed with the realloc() to shrink the list.
    */
    

    为什么字典(以及间接的集合)不采用类似的技巧,而是等待插入新条目?所描述的行为适用于Python 2.7和3.x(直到Python 3.7.0a0)。

    1 回复  |  直到 7 年前
        1
  •  12
  •   user2357112    7 年前

    这在中有所解释 Objects/dictnotes.txt

    可以调整大小。仅当 字典可以增长(并且可以 保持O(1),调整大小抖动或内存碎片的几率 减少了。特别是,一种通过以下方式清空字典的算法: 因为字典最终被丢弃了

    一个重要的考虑因素是收缩列表的缓冲区非常容易,而收缩dict的内部哈希表则是一个复杂得多的操作。