[Tutor] lambda vs def

Remco Gerlich scarblac@pino.selwerd.nl
Wed, 4 Jul 2001 07:39:37 +0200


On  0, VanL <van@lindbergs.org> wrote:
> I have been experimenting with functional programming styles using 
> python, and I was wondering about speed differences.  How different is
> 
> add = lambda x, y: x+y
> 
> from
> 
> def add(x, y): return x + y ?
> 
> Admittedly, this is a trivial example, but for functions called 
> repeatedly, it would add up.

They're exactly the same, as Roeland said (the difference is that
add.func_name is different).

I just wanted to add that operator.add is an existing function that does the
same, and it is written in C. And if you want it very fast, you first make
that add into a local variable (since local variable lookup is very fast);
so usually you'd do 'from operator import add' instead of the lambda or the
def.

> Also, how about eval()?  Is the cost for parsing prohibitive?

About 42, I'd say.

It all depends on your needs. Use the profile.run() function to
test how much time something takes, and compare.

Or better yet, don't. Don't worry about speed until your program works and
you find it is too slow. *Then* use the profiler to find out where the
problem is. It's likely that most of the time is spent in quite a small
region, and there you probably get the most gain from improving the
algorithm instead of trying to locally optimize the Python code.

-- 
Remco Gerlich