Generators vs. Functions?

Neil Schemenauer nas-usenet at arctrix.com
Sun Feb 5 11:14:54 EST 2006


Steven D'Aprano <steve at REMOVETHIScyber.com.au> wrote:
> Have you actually measured this, or are you just making a wild
> guess?

I haven't timed it until now but my guess it not so wild.  I'm
pretty familiar with the generator implementation (having written
the initial version of it).  In Python 2.3, resuming a generator
does a small amount of setup and then calls eval_frame().  Calling a
function does more setup work and then also calls eval_frame().

> Here is my test, using Python 2.3. I've tried to make the test as
> fair as possible, with the same number of name lookups in both
> pieces of test code.

On my machine t4 is faster than t3.  Your test is not so fair
because the generator is doing a "while" loop (executing more
bytecode instructions) while the function is just returning a value
(one instruction).

On your machine the function call may be faster due to CPU cache
effects or branch prediction.  In any case, the difference you are
trying to measure is extremely small.  Try adding some arguments to
the functions (especially keyword arguments).

What your test does show is that the speed difference should not
come into the decision of which construct to use.

  Neil



More information about the Python-list mailing list