[Python-ideas] Mitigating 'self.' Method Pollution

Anders J. Munch 2015 at jmunch.dk
Sun Jul 12 17:11:38 CEST 2015


Terry Reedy wrote:
 > Localization, which is not limited to self attributes, does two
 > things: it removes the need to continually type 'object.x'; it makes
 > the remaining code run faster.  I would be interested to know how
 > many faster local references are needed to make up for the overhead
 > of localization.

If you access the attribute just twice, that's enough for localisation to yield
a speedup.  Local variable access is just that much faster than attribute lookup.

$ python3 -V
Python 3.4.3Terry Reedy wrote:
 > Localization, which is not limited to self attributes, does two things: it
 > removes the need to continually type 'object.x'; it makes the remaining code
 > run faster.  I would be interested to know how many faster local references
 > are needed to make up for the overhead of localization.

If you access the attribute just twice, that's enough for localisation to yield
a speedup.  Local variable access is just that much faster than attribute lookup.

$ python3 -V
Python 3.4.3
$ python3 -m timeit -s "class C: pass" -s "c = C();c.x=1" "c.x;c.x"
10000000 loops, best of 3: 0.106 usec per loop
$ python3 -m timeit -s "class C: pass" -s "c = C();c.x=1" "x=c.x;x;x"
10000000 loops, best of 3: 0.0702 usec per loop

$ python -V
Python 2.7.3
$ python -m timeit -s "class C(object): pass" -s "c = C();c.x=1" "c.x;c.x"
10000000 loops, best of 3: 0.105 usec per loop
$ python -m timeit -s "class C(object): pass" -s "c = C();c.x=1" "x=c.x;x;x"
10000000 loops, best of 3: 0.082 usec per loop

regards, Anders



More information about the Python-ideas mailing list