appending to a list via properties

Peter Otten __peter__ at web.de
Sun Feb 12 10:59:58 EST 2006


[Alex Martelli]

> If you want to hoist for performance, you can hoist more:
> 
> appenders = foo.append, qux.append
> while some_condition:
>     for appender, anitem in zip(appenders, calculate_something()):
>         appender(anitem)

You are of course claiming a performance improvement over Carl's variant,
but looking back into the initial post

[Lonnie Princehouse]

>     foo = []
>     qux = []
> 
>     while some_condition:
>        a, b = calculate_something()
>        foo.append(a)
>        qux.append(b)

the original code looks like yours with the inner loop unrolled - a classic
measure for performance improvement. 

$ python -m timeit -s'ext = [].extend, [].extend' -s'def calc(): return (),
()' 'for ix, i in zip(ext, calc()): ix(i)'
100000 loops, best of 3: 2.79 usec per loop

$ python -m timeit -s'ax = [].extend; bx = [].extend' -s'def calc(): return
(), ()' 'a, b = calc(); ax(a); bx(b)'
1000000 loops, best of 3: 0.975 usec per loop

(I used extend instead of append() to avoid the effects of memory hogging)

I find the faster code more readable than yours - and Lonnie's cool hack -
so I'd leave it at that.

Peter




More information about the Python-list mailing list