Skip to content

Improved performance and arguably simpler code for dictionaries by changing the keys layout #142889

Description

@markshannon

Current layout

Currently the _dictkeysobject struct is laid out like this:

ptr ---->  +--------------+
           |     header   |
           +--------------+
           |    indices   |
           +--------------+
           |     keys     |
           +--------------+

which requires some relatively expensive calculation to find the start of the keys, as the indices are not only variable in number, but variable in size also.

Proposed layout

If instead it is laid out as follows:

           +--------------+
           |    indices   |
ptr ---->  +--------------+
           |     header   |
           +--------------+
           |     keys     |
           +--------------+

and the indices laid from highest to lowest with 0 just before ptr, finding the start of the keys is as simple as ptr->keys . Accessing an index is no slower, and the code barely any more complex.

Linked PRs

Activity

  1. added
    performancePerformance or resource usage
    interpreter-core(Objects, Python, Grammar, and Parser dirs)
    3.15bugs and security fixes
    on Dec 17, 2025
  2. rhettinger commented on Dec 17, 2025

    @rhettinger
    Contributor

    This seems like a reasonable experiment.

  3. added
    type-featureA feature request or enhancement
    and removed
    3.15bugs and security fixes
    on May 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)performancePerformance or resource usagetype-featureA feature request or enhancement

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions