python: class vs tuple huge memory overhead (?)

后端 未结 4 941
萌比男神i
萌比男神i 2021-02-20 12:16

I\'m storing a lot of complex data in tuples/lists, but would prefer to use small wrapper classes to make the data structures easier to understand, e.g.

class Pe         


        
4条回答
  •  遇见更好的自我
    2021-02-20 12:38

    Using __slots__ decreases the memory footprint quite a bit (from 1.7 GB to 625 MB in my test), since each instance no longer needs to hold a dict to store the attributes.

    class Person:
        __slots__ = ['first', 'last']
        def __init__(self, first, last):
            self.first = first
            self.last = last
    

    The drawback is that you can no longer add attributes to an instance after it is created; the class only provides memory for the attributes listed in the __slots__ attribute.

提交回复
热议问题