Why do two identical lists have a different memory footprint?

前端 未结 3 819
一整个雨季
一整个雨季 2020-11-28 06:15

I created two lists l1 and l2, but each one with a different creation method:

import sys

l1 = [None] * 10
l2 = [None for _ in rang         


        
3条回答
  •  生来不讨喜
    2020-11-28 06:35

    None is a block of memory, but it is not a pre-specified size. In addition to that, there is some extra spacing in an array between array elements. You can see this yourself by running:

    for ele in l2:
        print(sys.getsizeof(ele))
    
    >>>>16
    16
    16
    16
    16
    16
    16
    16
    16
    16
    

    Which does not total the size of l2, but rather is less.

    print(sys.getsizeof([None]))
    72
    

    And this is much greater than one tenth of the size of l1.

    Your numbers should vary depending on both the details of your operating system and the details of current memory usage in your operating system. The size of [None] can never be bigger than the available adjacent memory where the variable is set to be stored, and the variable may have to be moved if it is later dynamically allocated to be larger.

提交回复
热议问题