浅谈Python的_sizeof_()和getsizeof()

_sizeof_()

  • 返回内存中的大小,单位字节
 |  __sizeof__(self, /)
 |      Returns size in memory, in bytes.

getsizeof()

  • 这是sys模块的一个方法
  • 在pycharm中你只能看到如下内容,不过大致也是返回对象的大小,单位是字节
def getsizeof(p_object, default): # real signature unknown; restored from __doc__
    """
    getsizeof(object, default) -> int
    
    Return the size of object in bytes.
    """
    return 0
  • 2个貌似一样

测试代码

  • 代码1

    a = 1
    print(a.__sizeof__())  # 28 
    import sys
    print(sys.getsizeof(a)) # 28  嗯,一样
    
  • 代码2

    b = []
    print(b.__sizeof__())  # 40
    print(sys.getsizeof(b))   # 56 不一样(我在jupyter中执行的结果) # 如果你在pycharm中执行可能此处是 64
    
  • 代码3

    import sys
    l = []
    w =[1, 2]
    x =[4, 5, 7, 9]
    y =[2, 8, 6, 56, 45, 89, 88]
    
    print('sizeof:%d,getsize:%d' %(l.__sizeof__(),sys.getsizeof(l))) 
    print('sizeof:%d,getsize:%d' %(w.__sizeof__(),sys.getsizeof(w)))
    print('sizeof:%d,getsize:%d' %(x.__sizeof__(),sys.getsizeof(x)))
    
    # sizeof:40,getsize:64 # 此处就是在pycharm中执行的
    # sizeof:56,getsize:80
    # sizeof:72,getsize:96
    
  • getsizeof() 方法调用__sizeof__方法,但同时会附带一些额外的GC操作(arbage collector overhead). 因此前者的大小比后者要大一些

  • 列表初始化的时候是40,每加一个元素是8个字节

  • 代码大了之后,内存管理就显得非常重要了,现在仅作了解