lambda is slower than function call in python, why

前端 未结 3 1521
清酒与你
清酒与你 2021-02-20 18:20

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

3条回答
  •  死守一世寂寞
    2021-02-20 18:45

    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.

    Timing it

    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.

提交回复
热议问题