python list内存_python – list()使用比列表推导更多的内存

我认为你看到过度分配模式这是一个

sample from the source:

/* This over-allocates proportional to the list size, making room

* for additional growth. The over-allocation is mild, but is

* enough to give linear-time amortized behavior over a long

* sequence of appends() in the presence of a poorly-performing

* system realloc().

* The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...

*/

new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);

打印长度为0-88的列表推导的大小,您可以看到模式匹配:

# create comprehensions for sizes 0-88

comprehensions = [sys.getsizeof([1 for _ in range(l)]) for l in range(90)]

# only take those that resulted in growth compared to previous length

steps = zip(comprehensions, comprehensions[1:])

growths = [x for x in list(enumerate(steps)) if x[1][0] != x[1][1]]

# print the results:

for growth in growths:

print(growth)

结果(格式为(列表长度,(旧总大小,新的总大小))):

(0, (64, 96))

(4, (96, 128))

(8, (128, 192))

(16, (192, 264))

(25, (264, 344))

(35, (344, 432))

(46, (432, 528))

(58, (528, 640))

(72, (640, 768))

(88, (768, 912))

过度分配是出于性能原因,允许列表增长,而没有分配更多的内存与每增长(更好的amortized性能)。

与使用列表推导的区别的一个可能原因是列表推导不能确定性地计算生成的列表的大小,但list()可以。这意味着理解会持续增长列表,因为它使用过度分配填充它,直到最后填充它。

可能的是,一旦完成,就不会增长具有未使用的已分配节点的过度分配缓冲区(实际上,在大多数情况下,它不会失败过度分配目的)。

然而,list()无论列表大小如何都可以添加一些缓冲区,因为它预先知道最终列表大小。

另一个支持证据,也从源头,我们看到list comprehensions invoking LIST_APPEND,它指示使用list.resize,这反过来指示消费预分配缓冲区,而不知道它将被填充多少。这与您所看到的行为一致。

总而言之,list()将预先分配更多的节点作为列表大小的函数

>>> sys.getsizeof(list([1,2,3]))

60

>>> sys.getsizeof(list([1,2,3,4]))

64

列表解析不知道列表大小,因此它使用追加操作,因为它增长,耗尽预分配缓冲区:

# one item before filling pre-allocation buffer completely

>>> sys.getsizeof([i for i in [1,2,3]])

52

# fills pre-allocation buffer completely

# note that size did not change, we still have buffered unused nodes

>>> sys.getsizeof([i for i in [1,2,3,4]])

52

# grows pre-allocation buffer

>>> sys.getsizeof([i for i in [1,2,3,4,5]])

68

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值