I think lambda is faster than function call, but after testing, I find out that I am wrong. Function call is definitely faster than lambda call.
Can anybody tell me why
There's no difference in calling a lambda versus a function. A lambda is just a function created with a single expression and no name.
Say we have two identical functions, one created with a function definition, the other with a lambda expression:
def a():
return 222*333
b = lambda: 222*333
We see that both are the same type of function object and they both share equivalent byte-code:
>>> type(a)
>>> type(b)
>>> import dis
>>> dis.dis(a)
2 0 LOAD_CONST 3 (73926)
2 RETURN_VALUE
>>> dis.dis(b)
1 0 LOAD_CONST 3 (73926)
2 RETURN_VALUE
How can you speed that up? You don't. It's Python. It's pre-optimized for you. There's nothing more for you to do with this code.
Perhaps you could give it to another interpreter, or rewrite it in another language, but if you're sticking to Python, there's nothing more to do now.
Here's how I would examine the timings.
Timeit's timeit
and repeat
both take a callable:
import timeit
Note that timeit.repeat
takes a repeat
argument as well:
>>> min(timeit.repeat(a, repeat=100))
0.06456905393861234
>>> min(timeit.repeat(b, repeat=100))
0.06374448095448315
These differences are too small to be significant.