I've heard that __slots__
makes objects faster by avoiding a dictionary lookup. My confusion comes from Python being a dynamic language. In a static language, we avoid a dictionary lookup for a.test
by doing a compile-time optimisation to save the index in the instruction we run.
Now, in Python, a
could just as easily be another object that has a dictionary or a different set of attributes. It seems like we'll still have to do a dictionary lookup - the only difference seems to be that we only need one dictionary for the class, rather than a dictionary for each object.
With this rational,
- How does
__slots__
avoid a dictionary lookup? - Does slots make accessing objects faster?
__slots__
does not (significantly) speed up attribute access:The goal of using
__slots__
is to save memory; instead of using a.__dict__
mapping on the instance, the class has descriptors objects for each and every attribute named in__slots__
and instances have the attribute assigned wether or not they have an actual value:So python still has to look at the class for each attribute access on an instance of
Foo
(to find the descriptor). Any unknown attribute (say,Foo.ham
) will still result in Python looking through the class MRO to search for that attribute, and that includes dictionary searches. And you can still assign additional attributes to the class:The slot descriptors are created when the class is created, and access memory assigned to each instance to store and retrieve a reference to the associated value (the same chunk of memory that tracks instance reference counts and a reference back to the class object). Without slots, a descriptor for
__dict__
is used accessing a reference to adict
object in the same manner.It might speed up a program where you instantiate lots of objects of the same class, genuinely never change what attributes they have, and cache misses on all those duplicate dictionaries present a real performance problem.
This is really just a special case of the general situation where saving space sometimes saves time as well, where cache is the limiting factor.
So, it probably won't make accessing one object faster, but may speed up accessing many objects of the same type.
See also this question.