Skip to content

Compact layout of Plain Python Objects #72

Closed
@markshannon

Description

@markshannon

Plain Python Objects are, at the Python level, just a thin wrapper around a dictionary.
However, they are generally used as objects with common behavior across all objects of a class.

Consider the much overused example of Color:

class Color:
    def __init__(self, r, g, b):
        self.red = r
        self.green = g
        self.blue = b

This object has 3 words of data, but for a header size of H takes a huge (H+1)+(H+4)+5 == 2H+10 words assuming shared keys. Without shared keys it takes an even worse (H+1)+(H+4)+13+5 == 2H+23 words.

We can make two simple observations.

  1. The overhead of maintaining the dictionary, even if it is never used directly, is large.
  2. If we cannot share keys, things get even worse.

Which suggests two broad strategies:

  1. Avoid creating the dictionary, if we don't have to.
  2. Design the key sharing mechanism to reduce the number of cases where we lose sharing. It might be worth over-allocating the shared keys and values array a bit to achieve this. The compiler should be able to help us here. All self.attr accesses in a class's methods are visible to the compiler.

Ideally we would like to use H+3 words of memory, but even H+5 (allowing 2 slots for internal use or over allocation) would halve memory use.

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.13Things we intend to do for 3.13epic-compact-objectsReducing size of objects for 3.12

    Type

    No type

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions