Interning own classes like strings for speed and size?
Ulrich Eckhardt
doomster at knuut.de
Tue Dec 28 07:42:39 EST 2010
Steven D'Aprano wrote:
>>>> class InternedTuple(tuple):
> ... _cache = {}
> ... def __new__(cls, *args):
> ... t = super().__new__(cls, *args)
> ... return cls._cache.setdefault(t, t)
That looks good. The only thing that first bothered me is that it creates an
object and then possibly discards it again. However, there is no way around
that, since at least the key to the dict must be created for lookup. Since
key and value are the same here, this is even for free.
What I also found was that with the above, I can't provide __eq__ and __ne__
that just check for identity. If I do, the lookup in setdefault() will never
find an existing tuple and I will never save memory for a single object.
Thanks!
Uli
More information about the Python-list
mailing list