首页 > 解决方案 > 如果参数是列表对象,Python sys.getsizeof 是否也返回动态数组使用的内存

问题描述

python中的List是通过动态数组实现的。所以列表对象中有一个指针指向堆中的一个数组。源代码在这里

typedef struct {
PyObject_VAR_HEAD
/* Vector of pointers to list elements.  list[0] is ob_item[0], etc. */
PyObject **ob_item;

/* ob_item contains space for 'allocated' elements.  The number
 * currently in use is ob_size.
 * Invariants:
 *     0 <= ob_size <= allocated
 *     len(list) == ob_size
 *     ob_item == NULL implies ob_size == allocated == 0
 * list.sort() temporarily sets allocated to -1 to detect mutations.
 *
 * Items must normally not be NULL, except during construction when
 * the list is not yet visible outside the function that builds it.
 */
Py_ssize_t allocated;

} PyListObject;

所以我认为无论列表中有多少项,sys.getsizeof 都会返回一个常量值,因为列表对象只包含一个指针、一个 MACRO(PyObject_HEAD Py_ssize_t ob_size;) 和一个整数。

但是,我发现列表中 sys.getsizeof 的返回值随着列表中项目数的增加而增加。

例子:

sys.getsizeof([])                         #returns 72
sys.getsizeof([1])                        #returns 80
sys.getsizeof([x for x in xrange(1024)])  #returns 9032

为什么列表中 sys.getsizeof 的返回值不是常量?

标签: pythonpython-2.7memory-management

解决方案


推荐阅读