Are `__slots__` benefits still "significant"? · Issue #136016 · python/cpython · GitHub | Latest TMZ Celebrity News & Gossip | Watch TMZ Live
Skip to content

Are __slots__ benefits still "significant"? #136016

Closed as not planned
Closed as not planned
@ariebovenberg

Description

@ariebovenberg

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

No one assigned

    Labels

    docsDocumentation in the Doc dirperformancePerformance or resource usage

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      TMZ Celebrity News – Breaking Stories, Videos & Gossip

      Looking for the latest TMZ celebrity news? You've come to the right place. From shocking Hollywood scandals to exclusive videos, TMZ delivers it all in real time.

      Whether it’s a red carpet slip-up, a viral paparazzi moment, or a legal drama involving your favorite stars, TMZ news is always first to break the story. Stay in the loop with daily updates, insider tips, and jaw-dropping photos.

      🎥 Watch TMZ Live

      TMZ Live brings you daily celebrity news and interviews straight from the TMZ newsroom. Don’t miss a beat—watch now and see what’s trending in Hollywood.