我认为你看到过度分配模式这是来自源的样本:
/* 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)
结果(格式为list.resize):
(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))
过度分配是出于性能原因而完成的,允许列表增长,而不会在每次增长时分配更多内存(更好的摊销性能)。
使用列表理解存在差异的可能原因是列表理解不能确定性地计算生成列表的大小,但是list.resize可以。 这意味着理解将不断增加列表,因为它使用过度分配填充它,直到最终填充它。
一旦完成,有可能不会使用未使用的已分配节点增加过度分配缓冲区(实际上,在大多数情况下它不会,这会破坏过度分配的目的)。
但是,list.resize可以添加一些缓冲区,无论列表大小如何,因为它事先知道最终列表大小。
同样来自消息来源的另一个支持证据是,我们看到列表推导调用list.resize,其表示使用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