【问题标题】:How allocation of memory for `dict` in Python works?Python中“dict”的内存分配如何工作?
【发布时间】:2021-04-07 06:47:41
【问题描述】:

我在玩字典,发现了这个。

import sys

Square1 = {}
Square2 = {}
Square3 = {}

for i in range(1, 8):
    Square1[i] = i**2

for i in range(1, 11):
    Square2[i] = i**2

for i in range(1, 12):
    Square3[i] = i**2


print(sys.getsizeof(Square1), len(Square1))
print(sys.getsizeof(Square2), len(Square2))
print(sys.getsizeof(Square3), len(Square3))

输出:

196 7
196 10
344 11

字典长度 7 和 10 的大小与 196 相同,但长度 11 的大小为 344。 为什么它们是一样的?为什么尺寸会随着长度 11 而增加?字典大小在 Python 中是如何工作的?

【问题讨论】:

  • 您阅读过sys.getsizeof 的文档吗?

标签: python dictionary hashmap size


【解决方案1】:

当您创建一个空字典时,它会为它可以存储的初始几个引用预先分配块内存。随着字典添加更多的键值对,它需要更多的内存。

但它不会随着每次添加而增长;每次它需要更多空间时,它会添加一些内存块,可以容纳“X”个键值对,一旦“X”个量被填充,另一块内存被分配给字典。

这是一个显示变化的示例代码是字典的大小随着键数的增加

import sys

my_dict = {}
print("Size with {} keys:\t {}".format(0, sys.getsizeof(my_dict)))

for i in range(21):
    my_dict[i] = ''
    print("Size with {} keys:\t {}".format(i+1, sys.getsizeof(my_dict)))

这是 Python 3.6.2 中的输出:

#same size for key count 0 - 5 : 240 Bytes
Size with 0 keys:    240
Size with 1 keys:    240
Size with 2 keys:    240
Size with 3 keys:    240
Size with 4 keys:    240
Size with 5 keys:    240

#same size for key count 6 - 10 : 360 Bytes
Size with 6 keys:    368
Size with 7 keys:    368
Size with 8 keys:    368
Size with 9 keys:    368
Size with 10 keys:   368

#same size for key count 11 - 20 : 648 Bytes
Size with 11 keys:   648
Size with 12 keys:   648
Size with 13 keys:   648
Size with 14 keys:   648
Size with 15 keys:   648
Size with 16 keys:   648
Size with 17 keys:   648
Size with 18 keys:   648
Size with 19 keys:   648
Size with 20 keys:   648

此外,字典仅存储包含键和值的内存引用,而不将键值本身存储为dict 对象的一部分。所以数据的类型和大小都不会影响字典的sys.getsizeof()的结果。

例如,以下两个字典的大小都是 280 字节

>>> sys.getsizeof({'a': 'a'})
280

>>> sys.getsizeof({'a'*100000: 'a'*1000000})
280

但是'a' V/s 'a' * 1000000 的大小有以下区别:

>>> sys.getsizeof('a')
38

>>> sys.getsizeof('a'*1000000)
1000037

【讨论】:

    【解决方案2】:

    因为字典是一个容器,而 sys.getsizeof 不测量容器及其所有内容的大小。

    您可以使用此function 或更多信息here

    【讨论】:

      猜你喜欢
      • 2020-05-14
      • 2014-06-08
      • 2022-01-17
      • 2018-01-29
      • 2018-04-21
      • 2013-01-07
      • 2015-12-05
      • 1970-01-01
      相关资源
      最近更新 更多