python - 如果参数是列表对象,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 的返回值不是常量?
解决方案
推荐阅读
- string - 将字符串解析为二进制元组列表
- android - 对 Android 应用的测试和生产版本使用不同的后端
- python - 根据另一列的值在 pandas 的列中创建值列表
- c# - FastReport 嵌套 C# 类变量未使用
- python - 函数内字符串和整数名称的连接(python3)
- java - 远程调试:OpenJDK 11 上的 Wildfly 14 在端口 8787 上没有连接
- go - 为什么编译器会在这种情况下抱怨一个未使用的变量(当它被 fmt.Fprintf 使用时)?
- c# - 在 .csproj 中包含一个 .targets 文件以全局定义项目和 MSBuild 变量
- angular - Angular - 将管道作为变量传递
- ruby - 在 bash shell 中访问 ruby 属性