3 ms·
We can test memory usage in CPython (3.5)! >>> import collections >>> import sys >>> class A: ... def __init__(self, x, y): ... self.x =
by i80and 10y ago
We can test memory usage in CPython (3.5)!
>>> import collections
>>> import sys
>>> class A:
... def __init__(self, x, y):
... self.x = x
... self.y = y
...
>>> class B:
... __slots__ = ('x', 'y')
... def __init__(self, x, y):
... self.x = x
... self.y = y
...
>>> C = collections.namedtuple('C', ('x', 'y'))
>>> a = A(1, 1)
>>> b = B(1, 1)
>>> c = C(1, 1)
>>> d = {'x': 1, 'y': 1}
>>> sys.getsizeof(a) + sys.getsizeof(a.__dict__) # Plain object
344
>>> sys.getsizeof(b) + sys.getsizeof(b.__slots__) # Plain object with slots
120
>>> sys.getsizeof(c) # Named Tuple
64
>>> sys.getsizeof(d) # Dict
288
EDIT: Fixed a slew of measurement issues
EDIT2: Included size of __slots__ tuple
- SEJeff 10y agoIf you're using Python 3.5, use tracemalloc, it is much nicer for this sort of thing. https://docs.python.org/3/library/tracemalloc.html https://docs.python.org/3/library/tracemalloc.html