什么是string interning(字符串驻留)以及python中字符串的intern机制
Incomputer science, string interning is a method of storing only onecopy of each distinct string value, which must be immutable. Interning strings makes some stringprocessing tasks more time- or space-efficient at the cost of requiring moretime when the string is created or interned. The distinct values are stored ina string intern pool. --引自维基百科
也就是说,值同样的字符串对象仅仅会保存一份。是共用的,这也决定了字符串必须是不可变对象。想一想。就跟数值类型一样,同样的数值仅仅要保存一份即可了,不是必需用不同对象来区分。
python中的字符串採用了intern机制。会自己主动intern。
>>a = 'kzc'
>>b = 'k'+'zc'
>>id(a)
55704656
>>id(b)
55704656
能够看到。它们是同一个对象。
intern机制的优点是。须要值同样的字符串的时候(比方标识符)。直接从池里拿来用。避免频繁的创建和销毁。提升效率,节约内存。缺点是,拼接字符串、对字符串改动之类的影响性能。
由于是不可变的。所以对字符串改动不是inplace操作。要新建对象。
这也是为什么拼接多字符串的时候不建议用+而用join()。join()是先计算出全部字符串的长度,然后一一拷贝,仅仅new一次对象。
须要小心的坑。并非全部的字符串都会採用intern机制。仅仅包括下划线、数字、字母的字符串才会被intern。
>>a = 'hello world'
>>b = 'hello world'
>>id(a)
56400384
>>id(b)
56398336
这里由于有空格,全部没被intern。
可是为什么这么做呢?既然python内置函数intern()能显式对随意字符串进行intern。说明不是实现难度的问题。
答案在源代码stringobject.h中的凝视能够找到,
/* ... ... This is generally restricted tostrings that "looklike" Python identifiers, although the intern() builtincan be used to force interning of any string ... ... */
也就是说。仅仅对那些看起来像是python标识符的进行intern。
以下看另外一个坑。
例1.
>>'kz'+'c' is 'kzc'
True
例2.
>>s1 = 'kz'
>>s2 = 'kzc'
>>s1+'c' is 'kzc'
False
为什么第二个栗子是False,仅仅包括字母啊。不是应该被自己主动intern的么?
这是由于第一个栗子中,'kz'+'c'是在compile time求值的,被替换成了'kzc'.
而第二个栗子。s1+'c'是在run-time拼接的。导致没有被自己主动intern.
相关文章
- 【python教程入门学习】PyCharm下载和安装教程(包含配置Python解释器)
- 在pycharm中如何新建Python文件?_github下载的python源码项目怎么用
- Python常用代码_python画图代码大全
- python编程是什么-Python编程
- python调试工具ipdb基本命令
- Python入门系列(一)安装环境
- Python入门系列(十一)一篇搞定python操作MySQL数据库
- mac Python安装pybloomfilter 出现找不到libcrypto的问题
- python教程:用简单的Python编写Web应用程序
- 符合python命名规范的标识符是什么_Python标识符命名规范
- 【说站】Python yield实现迭代器协议
- 【说站】python判断变量的方法对比
- 【说站】python如何判断字符串被驻留
- python中的缩进快捷键_取消首行缩进快捷键
- Python安装失败_python第三方库安装失败
- 使用Python批量筛选上千个Excel文件中的某一行数据并另存为新Excel文件(上篇)
- python-Python与PostgreSQL数据库-使用Python执行PostgreSQL查询(二)
- Python字符串拼接(包含字符串拼接数字)
- Python MongoDB Spatial Query详解大数据
- 什么是协程,Python协程基本用法
- Python操作Redis实现数据持久化(python操作redis)
- 如何使用Linux下的pip快速管理Python包(linux怎么使用pip)
- Python脚本实现Linux系统管理及自动化部署(python写linux)
- 下的应用玩转Python:Linux下的Python应用之旅(python在linux)
- Linux下Python编程:从入门到精通(linux下python编程)
- c#中String和string的区别介绍