Measure Object Size Accurately in Python - Sys.GetSizeOf not functioning

前端 未结 6 1965
一向
一向 2020-11-30 12:31

I am trying to accurately/definitively find the size differences between two different classes in Python. They are both new style classes, save for one not having sl

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 13:12

    sys.getsizeof returns a number which is more specialized and less useful than people think. In fact, if you increase the number of attributes to six, your test3_obj remains at 32, but test4_obj jumps to 48 bytes. This is because getsizeof is returning the size of the PyObject structure implementing the type, which for test3_obj doesn't include the dict holding the attributes, but for test4_obj, the attributes aren't stored in a dict, they are stored in slots, so they are accounted for in the size.

    But a class defined with __slots__ takes less memory than a class without, precisely because there is no dict to hold the attributes.

    Why override __sizeof__? What are you really trying to accomplish?

提交回复
热议问题