how to make a generator use the last yielded value when it regains control

Felipe Almeida Lessa felipe.lessa at gmail.com
Mon Apr 10 13:17:24 EDT 2006


Em Seg, 2006-04-10 às 10:05 -0700, Lonnie Princehouse escreveu:
> I happen to think the recursive version is more elegant, but that's
> just me ;-)

It may be elegant, but it's not efficient when you talk about Python.
Method calls are expensive:

$ python2.4 -mtimeit 'pass'
10000000 loops, best of 3: 0.0585 usec per loop
$ python2.4 -mtimeit -s 'def x(): pass' 'x()'
1000000 loops, best of 3: 0.291 usec per loop
$ calc 0.291/0.0585
        ~4.97435897435897435897
$ calc 0.291-0.0585
        0.2325


This happens because of the dynamic nature of Python and its lack of
tail call optimization. IOW, avoid recursive methods when possible (I
usually write those for the first version of a method then rethink it
using a non-recursive approach), specially if they are part of a hot
spot.

-- 
Felipe.




More information about the Python-list mailing list