什麼是string interning(字串駐留)以及python中字串的intern機制,interningintern

來源:互聯網
上載者:User

什麼是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.

 


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.