为什么空字符串使用这么多字节?有人知道这 40 个字节中存储了什么吗?
解决方案在 Python 中,字符串是对象,因此值是对象本身的大小.所以这个大小总是大于字符串本身的大小.
来自 stringobject.h:
typedef struct {PyObject_VAR_HEAD长 ob_shash;int ob_sstate;字符 ob_sval[1];/* 不变量:* ob_sval 包含 'ob_size+1' 元素的空间.* ob_sval[ob_size] == 0.* ob_shash 是字符串的哈希值,如果尚未计算,则为 -1.* ob_sstate != 0 如果字符串对象在 stringobject.c 中*实习"字典;在这种情况下,两个参考* 从 'interned' 到这个对象在 ob_refcnt 中 * 不计算 *.*/pyStringObject;从这里您可以获得有关如何使用这些字节的一些线索:
- len(str)+1 个字节来存储字符串本身;
- 8 个字节的哈希值;
- (...)
Why does the empty string use so many bytes? Does anybody know what is stored in those 40 bytes?
解决方案In Python strings are objects, so that values is the size of the object itself. So this size will always be bigger than the string size itself.
From stringobject.h:
typedef struct { PyObject_VAR_HEAD long ob_shash; int ob_sstate; char ob_sval[1]; /* Invariants: * ob_sval contains space for 'ob_size+1' elements. * ob_sval[ob_size] == 0. * ob_shash is the hash of the string or -1 if not computed yet. * ob_sstate != 0 iff the string object is in stringobject.c's * 'interned' dictionary; in this case the two references * from 'interned' to this object are *not counted* in ob_refcnt. */ } PyStringObject;From here you can get some clues on how those bytes are used:
- len(str)+1 bytes to store the string itself;
- 8 bytes for the hash;
- (...)