Question: How efficient is using generators for coroutine-like problems?

Peter Hansen peter at engcorp.com
Thu Sep 23 19:26:37 CEST 2004


Carlos Ribeiro wrote:
> Now, just because I can do it does not mean it's a good idea :-) For
> particular cases, a measurement can be done. But I'm curious about the
> generic case. What is the performance penalty of using generators in
> situations as the ones shown above?

There shouldn't be a significant performance penalty, since
generators set up the stack frame when they are created and
reuse it, rather than creating a new one for each function
call.  They allow you to restructure your code more cleanly
but without taking a big hit from extra function calls.

But if you're concerned, there's always the timeit module
to tell you exactly what you're facing...

-Peter



More information about the Python-list mailing list