lambda is slower than function call in python, why

前端 未结 3 1520
清酒与你
清酒与你 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:51

    As pointed out above, your first test only profiles the time it takes to define a. It's actually never called.

    Lambda expressions and "normal" functions generate the exact same bytecode, as you can see if you use the dis module:

    def a(): return 10
    b = lambda: 10
    
    import dis
    
    >>> dis.dis(a)
    1           0 LOAD_CONST               1 (10)
                3 RETURN_VALUE
    >>> dis.dis(b)
    1           0 LOAD_CONST               1 (10)
                3 RETURN_VALUE
    

提交回复
热议问题