两个具有相同字符的Python字符串,a == b,可以共享内存,id(a)== id(b),或者可以在内存中两次,id(a)!= id(b).尝试
ab = "ab"
print id( ab ), id( "a"+"b" )
Run Code Online (Sandbox Code Playgroud)
在这里,Python认识到新创建的"a"+"b"与已经在内存中的"ab"相同 - 不错.
现在考虑一个N长的州名列表["亚利桑那州","阿拉斯加州","阿拉斯加州","加利福尼亚州......"(在我的案例中为N~500000).
我看到50个不同的id()s⇒每个字符串"Arizona"......只存储一次,很好.
但是将列表写入磁盘并再次读回:"相同"列表现在有N个不同的id()s,内存更多,见下文.
怎么 - 任何人都可以解释Python字符串内存分配?
""" when does Python allocate new memory for identical strings ?
ab = "ab"
print id( ab ), id( "a"+"b" ) # same !
list of N names from 50 states: 50 ids, mem ~ 4N + 50S, each string once
but list > file > mem again: N ids, mem ~ N * (4 + …Run Code Online (Sandbox Code Playgroud)