本文共 1221 字,大约阅读时间需要 4 分钟。
阅读目录
返回单位:字节
import sys >>> sys.getsizeof('3')38>>> sys.getsizeof('32')39>>> sys.getsizeof('325')40>>> sys.getsizeof(325)24>>> sys.getsizeof(1)24>>> sys.getsizeof(10000003250)24>>> sys.getsizeof(1000000000000000)24>>> sys.getsizeof(1000000000000000090)24>>> sys.getsizeof(10000000000000000900)36
可以看出字符串是比整形占用空间小的,且整形在一定范围内占用空间是一样的
import timeitimport sysdef f(): a, b, c = 3,2,1 return sys.getsizeof(a * 100 + b * 10 + c)def g(): a, b, c = 3,2,1 return sys.getsizeof(str(a) + str(b) + str(c))def f2(): a, b, c = 3,2,1 return a * 100 + b * 10 + cdef g2(): a, b, c = 3,2,1 return str(a) + str(b) + str(c)print min(timeit.repeat(f2))print min(timeit.repeat(g2))print f()print g()
结果
0.2967300415040.705047845842440
可以看出f()无论是从速度还是从内存占用都完胜g()
字典
>>> a{ 1: 'a', 2: 'b'}>>> sys.getsizeof(a)280>>> a[4] = "askjdfjllllllllllllll">>> a[5] = "askjdfjllllllllllllll">>> a{ 1: 'a', 2: 'b', 4: 'askjdfjllllllllllllll', 5: 'askjdfjllllllllllllll'}>>> sys.getsizeof(a)280>>> sys.getsizeof(a[1])38>>> for i in range(100):... a[i] = "fq08888888888" * 20... >>> len(a)100>>> sys.getsizeof(a)12568
本文转自jihite博客园博客,原文链接:http://www.cnblogs.com/kaituorensheng/p/6200467.html,如需转载请自行联系原作者