今天,我在 Python 2.7.13 中运行了下面给出的代码,发现当列表为空时,列表大小不是 0:
import sys
data = []
for k in range(n):
a = len(data)
b = sys.getsizeof(data)
print('Length:{0:3d};Size in bytes:{1:4d}'.format(a,b))
data.append(None)
我机器上的输出:
Length: 0; Size in bytes : 72
Length: 1; Size in bytes : 104
Length: 2; Size in bytes : 104
Length: 3; Size in bytes : 104
Length: 4; Size in bytes : 104
Length: 5; Size in bytes : 136
Length: 6; Size in bytes : 136
Length: 7; Size in bytes : 136
Length: 8; Size in bytes : 136
Length: 9; Size in bytes : 200
Length: 10; Size in bytes : 200
Length: 11; Size in bytes : 200
Length: 12; Size in bytes : 200
Length: 13; Size in bytes : 200
Length: 14; Size in bytes : 200
Length: 15; Size in bytes : 200
Length: 16; Size in bytes : 200
Length: 17; Size in bytes : 272
Length: 18; Size in bytes : 272
Length: 19; Size in bytes : 272
我想知道为什么会这样?
It seems that Python is reserving memory for something. What is that something??
最佳答案
因为从 sys.getsizeof
返回的列表大小并不只包括列表包含的元素。
Python 中的每个对象都由一个C
结构表示;这个结构包含指向使列表成为列表的所有事物的指针(主要是它的方法)。调用 sys.getsizeof
时也会考虑到这一点。
您可以随时查看 implementation of list.__sizeof__
在 GitHub 上 CPython 存储库的主分支中:
static PyObject *
list___sizeof___impl(PyListObject *self)
{
Py_ssize_t res;
res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
return PyLong_FromSsize_t(res);
}
(删除不相关的 arg clinic 输出。)
sizeof
function for 2.x
做同样的事情。
返回值res
还包括列表对象类型的大小_PyObject_SIZE(Py_Type(self))
。
由于 Python 中的一切都是对象,这种行为随处可见,例如,整数 0
:
>>> getsizeof(0)
24
虽然您通常不会想到这一点,但当您意识到 Python 中的所有内容都有“额外包袱”允许我们认为理所当然的行为时,这就非常有意义了。
关于python - 为什么空列表的大小不是 0 字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43120220/