sys.getsizeof(list) returns less than the sum of its elements

前端 未结 3 1438
滥情空心
滥情空心 2021-01-22 06:01

I\'m curious - why does the sys.getsizeof call return a smaller number for a list than the sum of its elements?

import sys
lst = [\"abcde\", \"fghij\", \"klmno\"         


        
3条回答
  •  孤独总比滥情好
    2021-01-22 06:11

    The memory of a numpy array a can be obtained by a.nbytes.

    sys.getsizeof shows "only the memory consumption directly attributed to the object [...], not the memory consumption of objects it refers to." (according to the documentation). In your case, it does not hold all the data. It can be seen with a.flags which outputs:

    C_CONTIGUOUS : True
    F_CONTIGUOUS : False
    OWNDATA : False
    WRITEABLE : True
    ALIGNED : True
    WRITEBACKIFCOPY : False
    UPDATEIFCOPY : False
    

    For the first array, it is instead:

    C_CONTIGUOUS : True
    F_CONTIGUOUS : False
    OWNDATA : True
    WRITEABLE : True
    ALIGNED : True
    WRITEBACKIFCOPY : False
    UPDATEIFCOPY : False
    

    The OWNDATA field being False explains why sys.getsizeof outputs only 128 bytes.

提交回复
热议问题