Gil*_*tes 10 python optimization performance memory-leaks
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> k = [i for i in xrange(9999999)]
>>> import sys
>>> sys.getsizeof(k)/1024/1024
38
>>>
Run Code Online (Sandbox Code Playgroud)

del k:
gc.collect():
为什么预期大小为38Mb的整数列表需要160Mb?
UPD: 这部分问题得到了解答(几乎是立即和多次:))
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> str = 'abcdefg'
>>> sys.getsizeof(str)
28
>>> k = []
>>> for i in xrange(9999999):
... k.append(str)
...
>>> sys.getsizeof(str)*9999999/1024/1024
267
Run Code Online (Sandbox Code Playgroud)
str在过去的例子中,大小是28,对比12.因此,预期的内存使用量为267Mb - 甚至超过整数.但它只需要~40Mb!
Arm*_*igo 14
sys.getsizeof()不是很有用,因为它通常只是你期望的一部分.在这种情况下,它考虑列表,但不是列表中的所有整数对象.该列表每个项目大约需要4个字节.整数对象各占12个字节.例如,如果您尝试这样做:
k = [42] * 9999999
print sys.getsizeof(k)
Run Code Online (Sandbox Code Playgroud)
你会看到列表仍然需要每个项目4个字节,即大约40MB,但因为所有项目都指向同一个整数对象42,所以总内存使用量不会超过40MB.