駐留機制是 Python 針對字元串文字的優化技術。它不會保存同一字元串 Literals 的多個副本,而是保存它的單個副本。這有助於有效使用內存並加快查找和比較速度。讓我們通過一些示例來了解它
import sys
s1 = 'Medium does not support basic HTML tables'
s2 = 'Medium does not support basic HTML tables'
print(s1 is s2) # false
print(id(s1)) # 139912277338320
print(id(s2)) # 140434884249808
s3 = sys.intern('Medium does not support basic HTML tables')
s4 = sys.intern('Medium does not support basic HTML tables')
print(s3 is s4) # true
sys.intern() 顯式地暫存一個字元串。S3 和 S4 使用 sys.intern 進行暫存,因此它們引用同一對象。當您處理大文本並需要節省內存時,這是一個很好的方法。
嘗試了以下作來明確不讓字元串 Literals 引用同一個對象,但它們總是這樣做。因為 Python 在這些情況下會自動駐留字元串。
s1 = 'a really large text'
s2 = 'a really large text' + ''
s3 = s1[:]
s4 = str('a really large text')
它不會為長字元串( >800 chars)、動態創建的字元串、範圍/時間相似性(就像這裡的相同腳本一樣)駐留。但是,字典中的字元串鍵也是同一個對象,這使得執行查找變得更加容易。
sample_dict = {
'name' : 'Harshit',
'gender': 'M'
}
another_dict = {
'name' : 'Novak',
'gender': 'M'
}
print(hex(id(another_dict.keys()))) # 0x7fb4bce718b0
print(hex(id(sample_dict.keys()))) # 0x7fb4bce718b0