返回单位:字节
sys.getsizeof()
import sys
>>> sys.getsizeof('') >>> sys.getsizeof('') >>> sys.getsizeof('') >>> sys.getsizeof() >>> sys.getsizeof() >>> sys.getsizeof() >>> sys.getsizeof() >>> sys.getsizeof() >>> sys.getsizeof()
可以看出字符串是比整形占用空间小的,且整形在一定范围内占用空间是一样的
对比
import timeit
import sys
def f():
a, b, c = ,,
return sys.getsizeof(a * + b * + c) def g():
a, b, c = ,,
return sys.getsizeof(str(a) + str(b) + str(c)) def f2():
a, b, c = ,,
return a * + b * + c def g2():
a, b, c = ,,
return str(a) + str(b) + str(c) print min(timeit.repeat(f2))
print min(timeit.repeat(g2))
print f()
print g()
结果
0.296730041504
0.70504784584
可以看出f()无论是从速度还是从内存占用都完胜g()
字典
>>> a
{: 'a', : 'b'}
>>> sys.getsizeof(a) >>> a[] = "askjdfjllllllllllllll"
>>> a[] = "askjdfjllllllllllllll"
>>> a
{: 'a', : 'b', : 'askjdfjllllllllllllll', : 'askjdfjllllllllllllll'}
>>> sys.getsizeof(a) >>> sys.getsizeof(a[]) >>> for i in range():
... a[i] = "fq08888888888" *
...
>>> len(a) >>> sys.getsizeof(a)