为什么Python2.7dict比python3dict占用更多空间?

2024-04-25 22:12:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我读过关于实现compact dictsRaymond Hettinger's new method。这解释了为什么python3.6中的dict比python2.7-3.5中的dict占用更少的内存。不过,Python2.7和3.3-3.5 dicts中使用的内存似乎有所不同。测试代码:

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之间节省的原因。在


Tags: 内存inimportnewforsysrangemethod
1条回答
网友
1楼 · 发布于 2024-04-25 22:12:49

原来这是一条红鲱鱼。增加dict大小的规则在cpython2.7-3.2和cpython3.3之间发生了变化,在cpython3.4中又发生了变化(尽管这种变化只适用于删除发生时)。我们可以使用以下代码来确定dict扩展的时间:

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:

^{pr2}$

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

请记住,dict在达到2/3满时会调整大小,我们可以看到cpython2.7dict实现在扩展时的大小是原来的四倍,而cpython3.5/3.6dict实现的大小只有原来的两倍。在

这在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
 */

相关问题 更多 >