Interning own classes like strings for speed and size?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Mon Dec 27 18:24:47 EST 2010
On Mon, 27 Dec 2010 12:05:10 +0100, Ulrich Eckhardt wrote:
> What I'm now considering is to only allow a single instance of these
> objects for each set of values, similar to interned strings. What I
> would gain is that I could safely compare objects for identity instead
> of equality. What I'm not yet sure is how much overhead that would give
> me and/or how to keep it low. The idea is to store each instance in a
> set and after creating a new object I would first look up an equal
> object in the global set and return that instead, otherwise add the new
> one.
Try this technique:
>>> class InternedTuple(tuple):
... _cache = {}
... def __new__(cls, *args):
... t = super().__new__(cls, *args)
... return cls._cache.setdefault(t, t)
...
>>>
>>>
>>> t1 = InternedTuple((1.0, 2.0))
>>> t2 = InternedTuple((0.0, 0.0))
>>> t3 = InternedTuple((1.0, 2.0))
>>>
>>> t1 is t2
False
>>> t1 is t3
True
>>> t1 == t2
False
>>> t1 == t3
True
--
Steven
More information about the Python-list
mailing list