How many bytes per element are there in a Python list (tuple)?

后端 未结 5 1922
醉酒成梦
醉酒成梦 2020-12-02 23:47

For example, how much memory is required to store a list of one million (32-bit) integers?

alist = range(1000000) # or list(range(1000000)) in Python 3.0
         


        
5条回答
  •  青春惊慌失措
    2020-12-03 00:43

    Addressing "tuple" part of the question

    Declaration of CPython's PyTuple in a typical build configuration boils down to this:

    struct PyTuple {
      size_t refcount; // tuple's reference count
      typeobject *type; // tuple type object
      size_t n_items; // number of items in tuple
      PyObject *items[1]; // contains space for n_items elements
    };
    

    Size of PyTuple instance is fixed during it's construction and cannot be changed afterwards. The number of bytes occupied by PyTuple can be calculated as

    sizeof(size_t) x 2 + sizeof(void*) x (n_items + 1).

    This gives shallow size of tuple. To get full size you also need to add total number of bytes consumed by object graph rooted in PyTuple::items[] array.

    It's worth noting that tuple construction routines make sure that only single instance of empty tuple is ever created (singleton).

    References: Python.h, object.h, tupleobject.h, tupleobject.c

提交回复
热议问题