List comprehensions performance

Alex Martelli aleaxit at yahoo.com
Thu Sep 30 14:13:04 EDT 2004


Bengt Richter <bokr at oz.net> wrote:
   ...
> >...but if the for loop is NOT equivalent (it doesn't accumulate results
> >into a resulting list), it's still faster.  As I posted:
> >
> >kallisti:~/cb alex$ python2.4 timeit.py -s'def f():pass' 'for x in
> >xrange(999): f()'
> >1000 loops, best of 3: 1.29e+03 usec per loop
> >kallisti:~/cb alex$ python2.4 timeit.py -s'def f():pass' '[f() for x in
> >xrange(999)]'
> >1000 loops, best of 3: 1.45e+03 usec per loop
> >
> >the LC is paying for the building of a list of 999 references to None,
> >which the for loop easily avoids, so the for loop is much faster here.
> 
> What if you abuse the LC so it makes an empty list? E.g.,
>     [None for x in xrange(999) if f() and False]

Now tell me, is timing so HARD...?!  This obfuscation times (on 2.4 and
the same old iBook as above) to 1.38e+03 usec per loop, still slower
than the plain old loop -- the if/and rigmarole costs...


Alex



More information about the Python-list mailing list