python中len()和sys.getsizeof()方法有什么区别?

2024-06-09 17:24:04 发布

您现在位置:Python中文网/ 问答频道 /正文

当我运行下面的代码时,得到的答案分别是3和36。

x ="abd"
print len(x)
print sys.getsizeof(x)

有人能给我解释一下他们之间的区别吗?


Tags: 答案代码lensysprint区别abdgetsizeof
1条回答
网友
1楼 · 发布于 2024-06-09 17:24:04

它们完全不是一回事。

^{}查询容器中包含的项目数。对于字符数为的字符串:

Return the length (the number of items) of an object. The argument may be a sequence (string, tuple or list) or a mapping (dictionary).

^{}另一方面返回对象的内存大小:

Return the size of an object in bytes. The object can be any type of object. All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific.

Python字符串对象不是简单的字符序列,每个字符1个字节。

具体来说,sys.getsizeof()函数包括垃圾收集器开销(如果有的话):

getsizeof() calls the object’s __sizeof__ method and adds an additional garbage collector overhead if the object is managed by the garbage collector.

不需要跟踪字符串对象(它们不能创建循环引用),但字符串对象确实需要比每个字符只需要字节更多的内存。在Python 2中,__sizeof__方法返回(在C代码中):

Py_ssize_t res;
res = PyStringObject_SIZE + PyString_GET_SIZE(v) * Py_TYPE(v)->tp_itemsize;
return PyInt_FromSsize_t(res);

其中,PyStringObject_SIZE是类型的C结构头大小,PyString_GET_SIZE基本上与len()相同,Py_TYPE(v)->tp_itemsize是每个字符的大小。在Python2.7中,对于字节字符串,每个字符的大小是1,但令人困惑的是PyStringObject_SIZE;在我的Mac上,这个大小是37字节:

>>> sys.getsizeof('')
37

对于unicode字符串,每个字符的大小增加到2或4(取决于编译选项)。在Python3.3和更新版本中,Unicode字符串每个字符占用1到4个字节,具体取决于字符串的内容

相关问题 更多 >