How do I determine the size of an object in Python?

前端 未结 13 1486
半阙折子戏
半阙折子戏 2020-11-21 21:53

I want to know how to get size of objects like a string, integer, etc. in Python.

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

13条回答
  •  误落风尘
    2020-11-21 22:36

    Python 3.8 (Q1 2019) will change some of the results of sys.getsizeof, as announced here by Raymond Hettinger:

    Python containers are 8 bytes smaller on 64-bit builds.

    tuple ()  48 -> 40       
    list  []  64 ->56
    set()    224 -> 216
    dict  {} 240 -> 232
    

    This comes after issue 33597 and Inada Naoki (methane)'s work around Compact PyGC_Head, and PR 7043

    This idea reduces PyGC_Head size to two words.

    Currently, PyGC_Head takes three words; gc_prev, gc_next, and gc_refcnt.

    • gc_refcnt is used when collecting, for trial deletion.
    • gc_prev is used for tracking and untracking.

    So if we can avoid tracking/untracking while trial deletion, gc_prev and gc_refcnt can share same memory space.

    See commit d5c875b:

    Removed one Py_ssize_t member from PyGC_Head.
    All GC tracked objects (e.g. tuple, list, dict) size is reduced 4 or 8 bytes.

提交回复
热议问题