【问题标题】:Why does Python2.7 dict use more space than Python3 dict?为什么 Python2.7 dict 比 Python3 dict 使用更多空间?
【发布时间】:2017-12-30 05:56:04
【问题描述】:

我读过关于实现compact dictsRaymond Hettinger's new method。这解释了为什么 Python 3.6 中的 dicts 比 Python 2.7-3.5 中的 dicts 使用更少的内存。然而,Python 2.7 和 3.3-3.5 字典中使用的内存似乎有所不同。测试代码:

import sys

d = {i: i for i in range(n)}
print(sys.getsizeof(d))
  • Python 2.7:12568
  • Python 3.5:6240
  • Python 3.6:4704

如上所述,我了解 3.5 和 3.6 之间的节省,但对 2.7 和 3.5 之间节省的原因感到好奇。

【问题讨论】:

  • 嗯,从来没有注意到这个,很好的发现。我不确定是否进行了更改,因此普通字典可以从组合表格中受益(请参阅我在实例字典上所做的问答here),但它可能值得研究。不过我对此表示怀疑:-)

标签: python python-2.7 python-3.x dictionary python-internals


【解决方案1】:

原来这是一条红鲱鱼。增加 dicts 大小的规则在 cPython 2.7 - 3.2 和 cPython 3.3 之间发生了变化,并且在 cPython 3.4 中再次发生了变化(尽管这种变化仅适用于发生删除时)。我们可以使用以下代码来确定字典何时展开:

import sys

size_old = 0
for n in range(512):
    d = {i: i for i in range(n)}
    size = sys.getsizeof(d)
    if size != size_old:
        print(n, size_old, size)
    size_old = size

Python 2.7:

(0, 0, 280)
(6, 280, 1048)
(22, 1048, 3352)
(86, 3352, 12568)

Python 3.5

0 0 288
6 288 480
12 480 864
22 864 1632
44 1632 3168
86 3168 6240

Python 3.6:

0 0 240
6 240 368
11 368 648
22 648 1184
43 1184 2280
86 2280 4704

请记住,当 dicts 达到 2/3 满时会调整大小,我们可以看到 cPython 2.7 dict 实现在扩展时大小增加了四倍,而 cPython 3.5/3.6 dict 实现的大小仅增加了一倍。

dict source code 的评论中对此进行了解释:

/* GROWTH_RATE. Growth rate upon hitting maximum load.
 * Currently set to used*2 + capacity/2.
 * This means that dicts double in size when growing without deletions,
 * but have more head room when the number of deletions is on a par with the
 * number of insertions.
 * Raising this to used*4 doubles memory consumption depending on the size of
 * the dictionary, but results in half the number of resizes, less effort to
 * resize.
 * GROWTH_RATE was set to used*4 up to version 3.2.
 * GROWTH_RATE was set to used*2 in version 3.3.0
 */

【讨论】:

  • 如果 Raymond Hettinger 看到这个问题并告诉我们他们为什么做出这样的改变,那就太好了......
  • @PM2Ring 我收到了next best thing
猜你喜欢
  • 1970-01-01
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
  • 2023-03-22
  • 1970-01-01
相关资源
最近更新 更多