Sub topic 5
Measuring memory savings honestly
This chapter assumes you know how an instance stores attributes in its __dict__ and how __slots__ replaces that dict with fixed slots. You should also be comfortable running short scripts and reading numeric output. The aim is to measure what slots save in a way you can trust, and to avoid claims the measurement does not support.
What `sys.getsizeof` reports
sys.getsizeof(obj) returns the size in bytes of the object's own memory block. It is shallow. It does not follow references, so it ignores everything the object points to. This matters for slots, because the saving comes from what lives inside the instance and beside it.
import sys
class Holder:
__slots__ = ("items",)
def __init__(self, items):
self.items = items
h = Holder(list(range(1000)))
print("holder:", sys.getsizeof(h))
print("list it points to:", sys.getsizeof(h.items))The holder is small and the list it references is much larger. getsizeof(h) never includes the list. For a slotted instance this is mostly fine, because the instance holds one pointer per slot and the values are separate objects. For a regular instance, the __dict__ is a separate object too, so you have to add it explicitly.
The rough per-instance comparison
The usual first measurement adds the instance size and its dict size for a regular class, and uses the instance size alone for a slotted class.
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))On most 64-bit CPython builds the slotted figure is clearly smaller. A slotted instance with two slots needs an object header plus one 8-byte pointer per slot. A regular instance needs its own header, a pointer to the dict, and a whole dict object.
The exact numbers depend on the Python version and implementation. They differ between CPython 3.8 and 3.12, and they are not the same on PyPy. Treat any single printed value as approximate, and compare the two numbers from the same interpreter only.
Why this comparison is only an estimate
Three things make the sum of two getsizeof calls unreliable.
- Key-sharing dictionaries. Since CPython 3.3, instances of the same class can share one table of keys. Each instance's dict then stores only its values.
getsizeof(plain.__dict__)reports the size of that dict object, which already benefits from the sharing. - Lazily created dicts. In CPython 3.11 and later, a regular instance can keep its attribute values inline in the object. It builds a real
__dict__object only when something asks for one. Callingplain.__dict__can therefore create a dict that would not otherwise exist. The measurement then charges the regular class for memory the program might never have used. - Allocator rounding. CPython's small-object allocator hands out blocks in fixed size classes. The bytes you ask for are not always the bytes you consume, so the reported sizes can be slightly lower than real usage.
None of this makes slots useless. It means the two-line sum is a sketch and not a benchmark.
Measuring a population with `tracemalloc`
A better approach is to build many instances and measure how much memory the allocations took. The standard library's tracemalloc tracks Python's memory allocations and reports the current traced total, which includes dicts, inline storage, and any other blocks the instances needed.
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, count=100_000):
tracemalloc.start()
before, _ = tracemalloc.get_traced_memory()
objects = [cls(1, 2) for _ in range(count)]
after, _ = tracemalloc.get_traced_memory()
tracemalloc.stop()
del objects
return (after - before) / count
plain = bytes_per_instance(PlainPoint)
slotted = bytes_per_instance(SlottedPoint)
print(f"plain: {plain:.1f} bytes per instance")
print(f"slotted: {slotted:.1f} bytes per instance")
print(f"ratio: {slotted / plain:.2f}")Several choices in this script are deliberate.
- The values
1and2are small integers that CPython caches. Both classes share the same integer objects, so the values add nothing to either side. If you usedrange(count)for the values, each class would also pay for new integer objects, which hides the difference you are trying to see. - The list holding the instances adds one 8-byte pointer per element. That cost is the same for both classes, so it does not change the comparison, but it does mean the printed numbers are slightly larger than the instance alone.
tracemalloc.stop()is called after the second reading, and the objects stay alive until after that point. If the list were freed first, the second reading would be wrong.- Using 100,000 instances reduces the effect of one-off allocations such as the shared key table.
Run it a few times and with a different Python version if you can. The ratio is more stable than the absolute bytes. State the ratio together with the interpreter version when you report it.
What `tracemalloc` costs you
tracemalloc slows the program down and adds its own bookkeeping memory. That bookkeeping is not counted in get_traced_memory, but the slowdown means you should never use the same run to measure speed. Measure memory and time in separate runs.
Choosing a measurement method
Different tools answer different questions. Pick the one that matches the claim you want to make.
| Method | What it measures | Good for | Main limitation |
|---|---|---|---|
| `sys.getsizeof` | One object's own block | Quick look at a single instance | Shallow, and does not follow references |
| `getsizeof` of instance plus `__dict__` | Rough regular-instance cost | Back-of-envelope estimate | Can create a dict that did not exist, and varies by version |
| `tracemalloc` | Python allocations over a period | Per-instance cost over many objects | Slows execution, and tracks only Python allocations |
| Process memory (RSS) | Whole-process memory from the operating system | Real impact on a running program | Includes everything else, and is noisy |
| Third-party deep sizers such as `pympler.asizeof` | An object plus everything it references | Whole object graphs | Extra dependency, and counts shared objects once |
For an honest claim about a real program, use both ends. Use tracemalloc to show the per-instance cost, and process memory to show whether the whole program benefits.
Counting what is not an instance
The per-instance figure is only part of a program's memory. Before attributing a saving to slots, look at what else the instances hold.
import tracemalloc
class PlainRecord:
def __init__(self, name, tags):
self.name = name
self.tags = tags
class SlottedRecord:
__slots__ = ("name", "tags")
def __init__(self, name, tags):
self.name = name
self.tags = tags
def total_bytes(cls, count=50_000):
tracemalloc.start()
before, _ = tracemalloc.get_traced_memory()
objects = [cls(f"item-{i}", [i, i + 1, i + 2]) for i in range(count)]
after, _ = tracemalloc.get_traced_memory()
tracemalloc.stop()
del objects
return after - before
plain_total = total_bytes(PlainRecord)
slotted_total = total_bytes(SlottedRecord)
saved = plain_total - slotted_total
print(f"plain total: {plain_total:,}")
print(f"slotted total: {slotted_total:,}")
print(f"saved: {saved:,} ({saved / plain_total:.0%} of plain)")Each record here owns a unique string and a unique three-element list. Both are the same in either class, so slots remove only the per-instance overhead. The percentage saved is much smaller than in the point example, because the shared payload dominates. The absolute bytes saved per instance stay about the same. The share of the total shrinks.
This is the most common way a slots claim gets overstated. A figure like "slots cut memory by 60%" is true for tiny objects holding small cached values. For objects that carry strings, lists, or other containers, the same change may save a few percent.
What the memory measurement does not tell you
Memory is one dimension. The measurement says nothing about these.
- Attribute access speed. Slot reads go through a descriptor on the class, and dict reads go through a lookup. Recent CPython versions optimise both heavily. Any difference is small and depends on the version, so measure it separately with
timeitif it matters to you. - Creation speed. Building many instances can be faster or slower with slots. Do not infer this from the memory result.
- Peak versus steady-state memory.
tracemallochere reports a steady figure after construction. A program that builds and discards many temporary instances has a different profile. - Memory returned to the operating system. Freed blocks often stay inside the allocator's arenas, so process memory may not drop even when Python objects are freed.
A checklist for an honest claim
- Name the interpreter and version, for example CPython 3.12 on 64-bit Linux.
- Use many instances, at least tens of thousands, and divide.
- Use the same attribute values for both classes so shared objects cancel out.
- Report the per-instance bytes and the ratio, not only one of them.
- Report the saving as a share of the whole workload, not only of the instance.
- Repeat the run a few times. If the numbers move by more than a few percent, say so.
- Keep memory and timing measurements in separate runs.
Common mistakes
- Comparing across versions. A slotted result from Python 3.9 against a regular result from Python 3.12 shows nothing about slots.
- Measuring one instance. A single object tells you almost nothing, because one-off costs such as the shared key table dominate.
- Letting values differ. If the regular class gets freshly built integers and the slotted class gets cached ones, the comparison is wrong before it starts.
- Counting the list of instances. Keeping the container out of the measurement, or including it for both classes equally, avoids a skewed ratio.
- Treating RSS changes as exact. Operating-system memory figures include interpreter startup, imported modules, and allocator behaviour. Use them to confirm the direction of a change, not its size.
Exercise
You measure 200,000 instances of a regular class and a slotted class with tracemalloc. Each instance holds one unique 1,000-character string. The slotted version uses about 100 bytes less per instance, and each instance already costs about 1,150 bytes in total. A teammate says "slots cut our memory by half". Is that claim supported, and what would you report?
Show answer
No. The saving is about 100 of 1,150 bytes per instance, which is under 9%, because the string payload is identical in both classes and dominates the total. Report the interpreter version, the per-instance saving of roughly 100 bytes, the ratio of about 0.91, and the share of whole-process memory. A claim of "half" would apply only to tiny instances holding cached values such as small integers.
Exercise
Why does the bytes_per_instance function use cls(1, 2) and not cls(i, i) with i from range(count)?
Show answer
Small integers such as 1 and 2 are cached, so both classes share the same value objects and add no memory. With range(count) values, every instance would also allocate new integer objects, which adds the same extra bytes to both classes and hides the per-instance difference you want to measure. Using constants keeps the comparison on the instance storage only.