# Structures

Michele Simionato michele.simionato at gmail.com
Tue Nov 4 14:04:54 CET 2008

```On Nov 4, 11:20 am, bearophileH... at lycos.com wrote:
> Michele Simionato:
>
> > No, slots have nothing to do with speed, they are a memory optimization.
>
> In many languages, often in Python too, the less memory you use/
> allocate the faster you go.
>
> In fact slots allow a speed increase too (in new style classes):
>
> from timeit import default_timer as clock
>
> class C1(object):
>     __slots__ = ["a", "b"]
>     def __init__(self, a, b):
>         self.a = a
>         self.a = b
>
> class C2(object):
>     def __init__(self, a, b):
>         self.a = a
>         self.a = b
>
> def main(N, test):
>     t0 = clock()
>
>     if test == 1:
>         [C1(ab, ab) for ab in xrange(N)]
>     elif test == 2:
>         [C2(ab, ab) for ab in xrange(N)]
>
>     t1 = clock()
>     print round(t1 - t0, 2)
>
> main(N=700*1000, test=1)
>
> Core duo 2 GHz:
> test=1 ==> 1.06 s
> test=2 ==> 3.0 s
>
> (700*1000 is the way I have found to write the 700_000 I was talking
> about, until we'll have a syntax for it.)
>
> Bye,
> bearophile

I did not expect such a large difference in instantiation time.
However I was thinking about
access time, and then the difference is not impressive (~20-25%):

from timeit import default_timer as clock

class C1(object):
__slots__ = ["a", "b"]
def __init__(self, a, b):
self.a = a
self.b = b

class C2(object):
def __init__(self, a, b):
self.a = a
self.b = b

def main(N, test):
t0 = clock()
if test == 'with slots':
c = C1(1, 2)
for _ in xrange(N):
(c.a, c.b)
elif test == 'without slots':
c = C2(1, 2)
for _ in xrange(N):
(c.a, c.b)
t1 = clock()
print test, round(t1 - t0, 3)

main(N=700*1000, test='with slots') # 0.152s
main(N=700*1000, test='without slots') #  0.195s

I mantain that one should use slots only as last resort, if the
speedup really justify having nonstandard classes.

```