Why __slots__ slows down attribute access?

Adam Skutt askutt at gmail.com
Tue Aug 23 07:26:10 EDT 2011


On Aug 23, 5:48 am, Jack <wujac... at gmail.com> 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.

No, they don't really show anything.  The default clocks used by
timeit lack the resolution to measure such things accurately; you're
measuring various noise sources on your system.  The range of 100
trials of 1million iterations on my system is 70.3 ms, which is 70ns
when divided by a million, which is about the size of the difference
you show.  A 70ns average difference between iterations is trivially
attributable to noise on a modern machine.

Run enough trials or just wait for the moon to move a bit, and I
wouldn't be terribly surprised if you got difference results.
Rebooting your machine might be enough to do it.

Adam

> D:\>d:\python-v3.1.2\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.237 usec per loop
>
> D:\>d:\python-v3.1.2\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.214 usec per loop
>
> D:\>d:\python-v2.6.4\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.26 usec per loop
>
> D:\>d:\python-v2.6.4\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.217 usec per loop




More information about the Python-list mailing list