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字符串对象不是简单的字符序列,每个字符1个字节。
具体来说,
sys.getsizeof()
函数包括垃圾收集器开销(如果有的话):不需要跟踪字符串对象(它们不能创建循环引用),但字符串对象确实需要比每个字符只需要字节更多的内存。在Python 2中,
__sizeof__
方法返回(在C代码中):其中,
PyStringObject_SIZE
是类型的C结构头大小,PyString_GET_SIZE
基本上与len()
相同,Py_TYPE(v)->tp_itemsize
是每个字符的大小。在Python2.7中,对于字节字符串,每个字符的大小是1,但令人困惑的是PyStringObject_SIZE
;在我的Mac上,这个大小是37字节:对于
unicode
字符串,每个字符的大小增加到2或4(取决于编译选项)。在Python3.3和更新版本中,Unicode字符串每个字符占用1到4个字节,具体取决于字符串的内容。相关问题 更多 >
编程相关推荐