J
Jack
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.
__slots__ are implemented at the class level by creating descriptors
(Implementing Descriptors) for each variable name. It makes a little
bit slower.
So __slots__ just saves memory space by preventing creation of
__dict__ and __weakref__ on each instance, while sacrifice performance
and inheritance flexibility.
http://groups.google.com/group/comp.lang.python/msg/6623e8b94b6d6934
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
by __slots__ .
http://groups.google.com/group/comp.lang.python/msg/c4e413c3d86d80be
That is wrong. The following tests show it is slower.
__slots__ are implemented at the class level by creating descriptors
(Implementing Descriptors) for each variable name. It makes a little
bit slower.
So __slots__ just saves memory space by preventing creation of
__dict__ and __weakref__ on each instance, while sacrifice performance
and inheritance flexibility.
http://groups.google.com/group/comp.lang.python/msg/6623e8b94b6d6934
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