__slots_ and inheritance

Alex Martelli aleax at aleax.it
Sat Apr 12 15:25:44 EDT 2003


Aahz wrote:

> In article <b7340h0r7m at enews1.newsguy.com>,
> Alex Martelli  <aleaxit at yahoo.com> wrote:
>>
>>__slots__ is, essentially, an optimization (in terms of memory
>>consumption) intended for classes that are likely to be created
>>in very large numbers: you give up the normal flexibility of
>>being able to add arbitrary attributes to an instance, and what
>>you gain in return is that you save one dictionary per instance
>>(dozens and dozens of bytes per instance -- that will, of course,
>>not be all that relevant unless the number of instances that are
>>around is at the very least in the tens of thousands).
> 
> More than that, because of the way modern computer architectures do
> caching, using __slots__ tends to speed up instance attribute access.
> This also is an optimization, but it's effective with even hundreds of
> instances, if you're rapidly switching between instances.

Yes, some TINY such effect can be observed:

[alex at lancelot python2.3]$ python -O timeit.py -s 'class X(object):' -s' def 
__init__(self): self.x=23' -s'xs=[X() for i in range(999)]' 'z=[x.x for x 
in xs]'
1000 loops, best of 3: 769 usec per loop
[alex at lancelot python2.3]$ python -O timeit.py -s 'class X(object):' -s' def 
__init__(self): self.x=23' -s'xs=[X() for i in range(999)]' 'z=[x.x for x 
in xs]'
1000 loops, best of 3: 778 usec per loop
[alex at lancelot python2.3]$ python -O timeit.py -s 'class X(object):' -s' 
__slots__="x"' -s' def __init__(self): self.x=23' -s'xs=[X() for i in 
range(999)]' 'z=[x.x for x in xs]'
1000 loops, best of 3: 682 usec per loop
[alex at lancelot python2.3]$ python -O timeit.py -s 'class X(object):' -s' 
__slots__="x"' -s' def __init__(self): self.x=23' -s'xs=[X() for i in 
range(999)]' 'z=[x.x for x in xs]'
1000 loops, best of 3: 684 usec per loop
[alex at lancelot python2.3]$

But such speedups of 10% to 20% or thereabouts are really "lost in the
noise" in just about any practical case, IMHO (differently from the 2 times
to 3 times speedups I've shown for creation of tens or hundreds of
thousands of instances -- that, I think, is roughly the level at which
optimization starts to be worth paying something substantial for -- and
in fact optimization of memory footprint has even higher potential gain,
though it's devilishly hard to explore it given current profiling tools...).


Alex





More information about the Python-list mailing list