Generators vs. Functions?

Magnus Lycka lycka at carmen.se
Sun Feb 5 14:49:46 EST 2006


Duncan Booth wrote:
> Steven D'Aprano wrote:
>>So on the basis of my tests, there is a small, but significant speed
>>advantage to _calling_ a function versus _resuming_ a generator.
> 
> I get the same, but the difference is much less on my system:

With Python 2.4? Doesn't surprise me a bit.

I tested with 2.3 (vanilla Red Hat EL4 install) and it seems Steven
used 2.3 as well. My little test was just an attempt to test a claim
that the setup time would be shorter for generator calls than for
function calls. It's so easy to test timing with Python, so it's
surprising that people speculate so much about theories with no
measurements.

Who knows what the call time ratios will be in Python 2.6?

I think the important point is the one Fredrik is making: You
won't have a function implementation or a generator implementation
with the same code body.

The other differences in the code will typically mean much more than
the call overhead. If we're in some nested loop where we call a
function so trivial that the call overhead makes performance suffer,
by all means, inline these few lines of code in the loop!



More information about the Python-list mailing list