Closed
Description
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.
- The overhead of maintaining the dictionary, even if it is never used directly, is large.
- If we cannot share keys, things get even worse.
Which suggests two broad strategies:
- Avoid creating the dictionary, if we don't have to.
- 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
Type
Projects
Status
Done