摘要:驻留机制是 Python 针对字符串文字的优化技术。它不会保存同一字符串 Literals 的多个副本,而是保存它的单个副本。这有助于有效使用内存并加快查找和比较速度。让我们通过一些示例来了解它
驻留机制是 Python 针对字符串文字的优化技术。它不会保存同一字符串 Literals 的多个副本,而是保存它的单个副本。这有助于有效使用内存并加快查找和比较速度。让我们通过一些示例来了解它
import syss1 = 'Medium does not support basic HTML tables's2 = 'Medium does not support basic HTML tables'print(s1 is s2) # falseprint(id(s1)) # 139912277338320print(id(s2)) # 140434884249808s3 = sys.intern('Medium does not support basic HTML tables')s4 = sys.intern('Medium does not support basic HTML tables')print(s3 is s4) # truesys.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))) # 0x7fb4bce718b0print(hex(id(sample_dict.keys))) # 0x7fb4bce718b0来源:自由坦荡的湖泊AI一点号