I can see 2 possible reasons:
item * item
yields the same result as item ** 2
, but you're making an assumption about implementation of **
operator. Still, more important reason is...
lambda
is really a function - it has the same closure as a function you'd declare with def
in the same scope, and in the same way as such function, it will get it's own stack frame when executed. Creating, pushing and dropping such frame take time and this is probably what introduces such a big overhead. Quoting from here:
Semantically, they (lambdas) are just syntactic sugar for a normal
function definition.
Try benchmarking following calculations:
- inline
item*item
- inline
item **2
- usage of
def foo(x): return x*x
- usage of
def foo(x): return x**2
- usage of
lambda x: x*x
- usage of
lambda x: x**2
and you'll figure out real reasons (please share these results too, I'm sorta interested myself). I'd expect 2 first ways to be similiar in efficiency, and following 4 also similiar to each other, but slower by few orders of magnitude than those inline ones.
Also: use timeit
intead of time.time()
- it is more reliable. Here's a wider list of possibilities when it comes to measuring time of execution, though I'd really recommend timeit
, as it is created exactly for the kind of job that you want to do here.