为什么两个相同的列表具有不同的内存占用量? [英] Why do two identical lists have a different memory footprint?

查看:90
本文介绍了为什么两个相同的列表具有不同的内存占用量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了两个列表l1l2,但是每个列表都有不同的创建方法:

I created two lists l1 and l2, but each one with a different creation method:

import sys

l1 = [None] * 10
l2 = [None for _ in range(10)]

print('Size of l1 =', sys.getsizeof(l1))
print('Size of l2 =', sys.getsizeof(l2))

但是输出使我感到惊讶:

But the output surprised me:

Size of l1 = 144
Size of l2 = 192

使用列表推导创建的列表在内存中更大,但是在Python中这两个列表是相同的.

The list created with a list comprehension is a bigger size in memory, but the two lists are identical in Python otherwise.

那是为什么?这是CPython内部的东西,还是其他解释?

Why is that? Is this some CPython internal thing, or some other explanation?

推荐答案

编写[None] * 10时,Python知道它将需要一个正好包含10个对象的列表,因此它恰好分配了该对象.

When you write [None] * 10, Python knows that it will need a list of exactly 10 objects, so it allocates exactly that.

当您使用列表推导时,Python不知道它将需要多少.因此,随着元素的添加,列表逐渐增加.对于每个重新分配,它分配的空间都比立即需要的要多,因此不必为每个元素重新分配.结果列表可能会比需要的大一些.

When you use a list comprehension, Python doesn't know how much it will need. So it gradually grows the list as elements are added. For each reallocation it allocates more room than is immediately needed, so that it doesn't have to reallocate for each element. The resulting list is likely to be somewhat bigger than needed.

比较以相似大小创建的列表时,您会看到此行为:

You can see this behavior when comparing lists created with similar sizes:

>>> sys.getsizeof([None]*15)
184
>>> sys.getsizeof([None]*16)
192
>>> sys.getsizeof([None for _ in range(15)])
192
>>> sys.getsizeof([None for _ in range(16)])
192
>>> sys.getsizeof([None for _ in range(17)])
264

您可以看到第一种方法只分配需要的内容,而第二种则周期性地增长.在此示例中,它为16个元素分配了足够的内存,并且在达到第17个元素时不得不重新分配.

You can see that the first method allocates just what is needed, while the second one grows periodically. In this example, it allocates enough for 16 elements, and had to reallocate when reaching the 17th.

这篇关于为什么两个相同的列表具有不同的内存占用量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆