在 Python 中常常經過內存池化技術來提升其性能,那麼問題來了,在什麼狀況下會池化呢? 讓咱們經過幾個例子進行一下理解一下.html
在查看例子以前,首先要提 python 中的一個函數 id(),讓咱們看一下函數說明:python
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 值同樣,能夠說着兩個對象是相同的了.bash
example 00ide
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 01post
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)
輸出結果:ui
>>> a = "magic_string" >>> b = "magic" + "_" + "string" >>> print(id(a),id(b)) 2114887161136 2114887161136 >>> print(a is b) True
example 03code
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 的字符串池化有個大概的認識,咱們這裏作個簡單的總結: