Building CPython

Chris Angelico rosuav at gmail.com
Fri May 15 22:15:44 EDT 2015


On Sat, May 16, 2015 at 11:55 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> but in Python's case it has to be resolved at run-time, so if you care about
> speed, you should try to avoid long chains of dots in performance critical
> loops. E.g. instead of:
>
>     for x in sequence:
>         foo.bar.baz.foobar.spam.eggs.cheese(x)
>
> you can write:
>
>     cheese = foo.bar.baz.foobar.spam.eggs.cheese
>     for x in sequence:
>         cheese(x)

Like all advice, of course, this should not be taken on its own. Some
code tries to avoid long chains of dots by adding wrapper methods:

for x in sequence:
    foo.cheese(x)

where foo.cheese() delegates to self.bar.cheese() and so on down the
line. That, of course, will be far FAR slower, in pretty much any
language (unless the compiler can in-line the code completely, in
which case it's effectively being optimized down to the original
anyway); the dots aren't as bad as you might think :)

Just always remember the one cardinal rule of optimization: MEASURE
FIRST. You have no idea how slow something is until you measure it.

(I'm not addressing my comments to Steven here, who I'm fairly sure is
aware of all of this(!), but it's his post that gave the example that
I'm quoting.)

ChrisA



More information about the Python-list mailing list