Sub topic 5
Measuring memory savings honestly
This chapter assumes you know how an instance's __dict__ works and how __slots__ is declared, both covered in earlier chapters. Here you will measure what slots save, see where the usual measurements mislead, and learn to report a result without overstating it.
Why a quick check can mislead
The claim "slots save memory" is true in many cases, but the size of the saving depends on the Python version, the number of attributes, and what you count. A single sys.getsizeof call does not tell the whole story, for two reasons:
sys.getsizeof(obj)reports only the object itself. It does not follow references to the objects it points to, and it does not include the instance__dict__.- Recent CPython versions optimize regular instances. They may share key tables between instances and store values inline, so the cost of a
__dict__is lower than older tutorials claim.
A first, rough comparison
To compare per-instance cost, add the object's size to the size of its __dict__. A slotted object has no __dict__, so its size is the object's size alone.
import sys
class PlainPoint:
def __init__(self, x, y):
self.x = x
self.y = y
class SlottedPoint:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
plain = PlainPoint(1, 2)
slotted = SlottedPoint(1, 2)
print("plain:", sys.getsizeof(plain) + sys.getsizeof(plain.__dict__))
print("slotted:", sys.getsizeof(slotted))The slotted figure will be clearly smaller, but the exact numbers differ between Python versions and implementations. Treat them as approximate. Reading plain.__dict__ can also force CPython to build a real dictionary that it might otherwise have avoided, so this sum can overstate what a plain instance costs in normal use.
Measuring allocations with tracemalloc
A better method is to create many instances and ask the interpreter how much memory it allocated. The standard library module tracemalloc tracks memory allocated by Python code.
import tracemalloc
class PlainPoint:
def __init__(self, x, y):
self.x = x
self.y = y
class SlottedPoint:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
def bytes_per_instance(cls, n=100_000):
tracemalloc.start()
before = tracemalloc.get_traced_memory()[0]
items = [cls(i, i) for i in range(n)]
after = tracemalloc.get_traced_memory()[0]
tracemalloc.stop()
assert len(items) == n
return (after - before) / n
print("plain: ", round(bytes_per_instance(PlainPoint)), "bytes")
print("slotted:", round(bytes_per_instance(SlottedPoint)), "bytes")The items list must stay alive while you take the second reading. Otherwise the instances are freed and you measure nothing.
This number includes more than the instance itself:
- The
intobjects stored in the attributes. Both classes hold the same ints, so they cancel out in a comparison. - One pointer per instance in the
itemslist. This is also the same for both classes.
Because these costs are the same on both sides, the difference between the two results is the part that slots changed. The absolute numbers are not the saving.
What to report
A saving per instance only matters when multiplied by how many instances you have. Use the measurement to answer a concrete question, such as "how much memory do 5 million of these objects use?"
| Question | What to measure |
|---|---|
| How much does one instance cost? | `tracemalloc` difference divided by `n`, for both classes |
| Does it matter for my program? | Peak memory of the real workload, with and without slots |
| Is the result stable? | Repeat on the Python version you deploy |
Common mistakes
- Comparing
sys.getsizeof(plain)withsys.getsizeof(slotted)and forgetting the__dict__. This makes slots look worse or better than they are. - Measuring a single instance. Allocator rounding and cached small objects distort a sample of one.
- Running the test on one Python version and assuming the result holds on another.
- Reporting memory savings without checking that attribute access speed and flexibility still meet your needs. Those are covered in the final chapter.
Exercise
In the tracemalloc example, why does bytes_per_instance keep the instances in the items list instead of discarding them, and why does the comparison between the two classes still make sense even though each result includes the stored ints and the list pointer?
Show answer
The instances must stay alive until the second reading. If they were freed, the traced memory would drop back and the measurement would show almost nothing. The comparison still works because the ints and the list pointer are the same for both classes, so they cancel out in the difference. What remains is the part that changed: the cost of the per-instance __dict__ versus fixed slots.