什麼是string interning(字串駐留)以及python中字串的intern機制,interningintern
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.