What is the difference between len() and sys.getsizeof() methods in python?
当我运行下面的代码时,我分别得到3和36作为答案。
1 2 3 | x ="abd" print len(x) print sys.getsizeof(x) |
有人能给我解释一下他们之间的区别吗?
它们根本不是一回事。
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个字节。
具体来说,
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中,
1 2 3 | Py_ssize_t res; res = PyStringObject_SIZE + PyString_GET_SIZE(v) * Py_TYPE(v)->tp_itemsize; return PyInt_FromSsize_t(res); |
其中
1 2 | >>> sys.getsizeof('') 37 |
对于