小编给大家分享一下Python 字符串池化的前提,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!
前言
在 Python 中经常通过内存池化技术来提高其性能,那么问题来了,在什么情况下会池化呢; 让我们通过几个例子进行一下理解一下.
预备知识
在查看例子之前,首先要提 python 中的一个函数 id(),让我们看一下函数说明:
id(obj, /) Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (CPython uses the object \'s memory address.)
通过上述说明,可以得知 id() 将会返回对像的唯一标识,在 CPython 中将会返回内存地址,也就是说如果两个对象 的 id 值一样,可以说着两个对象是相同的了.
例子
example 00
a = "" b = "" print(id(a),id(b)) print(a is b)
输出结果:
>>> a = ""
>>> b = ""
>>> print(id(a),id(b))
2114853370544 2114853370544
>>> print(a is b)
True
example 01
a = "a" b = "a" print(id(a),id(b)) print(a is b)
输出结果:
>>> a = "a"
>>> b = "a"
>>> print(id(a),id(b))
2114883022608 2114883022608
>>> print(a is b)
True
example 02
a = "magic_string" b = "magic" + "_" + "string" print(id(a),id(b)) print(a is b)
输出结果:
>>> a = "magic_string"
>>> b = "magic" + "_" + "string"
>>> print(id(a),id(b))
2114887161136 2114887161136
>>> print(a is b)
True
example 03
a = "magic!" b = "mgaic!" print(id(a),id(b)) print(a is b)
输出结果:
>>> a = "magic!"
>>> b = "mgaic!"
>>> print(id(a),id(b))
2114885855416 2114889455408
>>> print(a is b)
False
example 04
a,b = "magic!","magic!" print(id(a),id(b)) print(a is b)
输出结果:
>>> a,b = "magic!","magic!"
>>> print(id(a),id(b))
2114885691912 2114885691912
>>> print(a is b)
True
example 05
a = "!" b = "!" print(id(a),id(b)) print(a is b)
输出结果:
>>> a = "!"
>>> b = "!"
>>> print(id(a),id(b))
140564571922024 140564571922024
>>> print(a is b)
True
example 06
print(a*20 is 'aaaaaaaaaaaaaaaaaaaa') print(a*21 is 'aaaaaaaaaaaaaaaaaaaaa')
输出结果:
>>> print(a*20 is 'aaaaaaaaaaaaaaaaaaaa')
False
>>> print(a*21 is 'aaaaaaaaaaaaaaaaaaaaa')
False
通过上述 7 个例子,我们不难对 python 的字符串池化有个大概的认识,我们这里做个简单的总结:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。