Why __slots__ slows down attribute access?

John-John Tedro johnjohn.tedro at gmail.com
Tue Aug 23 06:57:05 EDT 2011


On Tue, Aug 23, 2011 at 12:26 PM, Peter Otten <__peter__ at web.de> wrote:

> Jack wrote:
>
> > People have illusion that it is faster to visit the attribute defined
> > by __slots__ .
> > http://groups.google.com/group/comp.lang.python/msg/c4e413c3d86d80be
> >
> > That is wrong. The following tests show it is slower.
>
> Not so fast. Here's what I get (python2.6.4, 64 bit):
>
> $ python  -mtimeit -s "class A(object): __slots__ = ('a', 'b', 'c')" -s
> "inst = A()" "inst.a=5; inst.b=6; inst.c=7"
> 1000000 loops, best of 3: 0.324 usec per loop
>
> $ python  -mtimeit -s "class A(object): pass" -s "inst = A()" "inst.a=5;
> inst.b=6; inst.c=7"
> 1000000 loops, best of 3: 0.393 usec per loop
>
> Now what?
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

This is what I get on a 64 bit Linux 2.6.39

script:
for v in 2.6 2.7 3.2; do
  python$v --version
  echo -n "(slots)   = ";
  python$v -mtimeit -s "class A(object): __slots__ = ('a', 'b', 'c')" -s
"inst = A()" "inst.a=5; inst.b=6; inst.c=7";
  echo -n "(regular) = ";
  python$v -mtimeit -s "class A(object): pass" -s "inst = A()" "inst.a=5;
inst.b=6; inst.c=7";
done

output:
Python 2.6.5
(slots)   = 1000000 loops, best of 3: 0.219 usec per loop
(regular) = 1000000 loops, best of 3: 0.231 usec per loop
Python 2.7.2
(slots)   = 1000000 loops, best of 3: 0.244 usec per loop
(regular) = 1000000 loops, best of 3: 0.285 usec per loop
Python 3.2
(slots)   = 1000000 loops, best of 3: 0.193 usec per loop
(regular) = 1000000 loops, best of 3: 0.224 usec per loop

-- John-John Tedro
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110823/192fd5fc/attachment-0001.html>


More information about the Python-list mailing list