python源码剖析笔记(三)

xiaoxiao2021-02-27  307

python源码剖析笔记(三)

字符串对象

定义:

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;
PyStringObject对象创建
1.通过str创建,2.通过str+size创建字符串最大长度不能超过PY_SSIZT_T_MAX定义的值,在win32下该值为2G。空字符串对应一个nullstring,长度为1的单个字符会使用内部缓存池中的字符串对象,其它字符串会使用内部intern缓存的字符串或申请新的字符串对象

intern机制 将字符串通过内部PyDict对象缓存起来,再将来要创建相同字符串时再返回缓存的字符串,以达到节省内存的目的 字符缓冲池 以静态变量的形式存在,python初始化以后,缓冲池中的所有PyStringObject指针都为空,1.创建字符对象,2.对字符对象进行intern操作,3.将对象缓存到缓冲池characters中。 字符串效率问题 多个字符串连接,如果使用"+"则会在每次字符串相加时创建一个字符串对象,申请n-1次内存,使用join则会统计数组中字符串对象的个数和总长度,只进行一次内存申请。

转载请注明原文地址: https://www.6miu.com/read-5353.html

最新回复(0)