Description
Documentation
The __slots__
documentation states:
The space saved over using
__dict__
can be significant. Attribute lookup speed can be significantly improved as well.
In meticulous benchmarks, I've found the benefits (both memory and lookup speed) to be more modest in Python versions 3.11 and later. Perhaps the documentation should be updated to reflect this? Or maybe I'm missing something? Details below.
Memory Savings
Due to the optimizations to object layout introduced in Python 3.11, the memory savings from using __slots__
seem to be reduced. The exact savings depend on the number of attributes defined in the class. Below is a table showing the lower and upper bounds of memory savings of using __slots__
over __dict__
(in bytes per object instance).
version | min. memory savings | max memory savings |
---|---|---|
3.9 | 80 | 216 |
3.10 | 80 | 216 |
3.11 | 40 | 64 |
3.12 | 32 | 56 |
3.13 | 40 | 64 |
(see bottom of the post for the benchmarking code used to generate these numbers)
Lookup speed
Two observations:
- The speed boost is modest on Python 3.11 and later.
- The speed boost is negligible when using an optimized Python build
(--enable-optimizations --with-lto
).
version | speed boost | speed boost (optimized Python build) |
---|---|---|
3.9 | 62% | 4% |
3.10 | 52% | 8% |
3.11 | 13% | 4% |
3.12 | 15% | 0% |
3.13 | 3% | 3% |
The benchmarking code
The code can be found here: https://github.com/ariebovenberg/slots-bench
edit: formatting
Metadata
Metadata
Assignees
Projects
Status