Python efficiency of and vs multiple ifs

后端 未结 5 873
太阳男子
太阳男子 2021-02-07 05:32

Is there an efficiency difference between using and in an if statement and using multiple if statements? In other words, is something like

if expr1 == expr2 and         


        
5条回答
  •  鱼传尺愫
    2021-02-07 06:17

    When in doubt, you can check what does python compile your statements in, using dis module:

    >>> import dis
    >>> def test1():
    ...     if expr1 == expr2 and expr3==expr4:
    ...        dostuff()
    ... 
    >>> def test2():
    ...     if expr1 == expr2:
    ...        if expr3 == expr4:
    ...           dostuff()
    ... 
    >>> dis.dis(test1)
      2           0 LOAD_GLOBAL              0 (expr1)
                  3 LOAD_GLOBAL              1 (expr2)
                  6 COMPARE_OP               2 (==)
                  9 JUMP_IF_FALSE           24 (to 36)
                 12 POP_TOP             
                 13 LOAD_GLOBAL              2 (expr3)
                 16 LOAD_GLOBAL              3 (expr4)
                 19 COMPARE_OP               2 (==)
                 22 JUMP_IF_FALSE           11 (to 36)
                 25 POP_TOP             
    
      3          26 LOAD_GLOBAL              4 (dostuff)
                 29 CALL_FUNCTION            0
                 32 POP_TOP             
                 33 JUMP_FORWARD             1 (to 37)
            >>   36 POP_TOP             
            >>   37 LOAD_CONST               0 (None)
                 40 RETURN_VALUE        
    >>> dis.dis(test2)
      2           0 LOAD_GLOBAL              0 (expr1)
                  3 LOAD_GLOBAL              1 (expr2)
                  6 COMPARE_OP               2 (==)
                  9 JUMP_IF_FALSE           28 (to 40)
                 12 POP_TOP             
    
      3          13 LOAD_GLOBAL              2 (expr3)
                 16 LOAD_GLOBAL              3 (expr4)
                 19 COMPARE_OP               2 (==)
                 22 JUMP_IF_FALSE           11 (to 36)
                 25 POP_TOP             
    
      4          26 LOAD_GLOBAL              4 (dostuff)
                 29 CALL_FUNCTION            0
                 32 POP_TOP             
                 33 JUMP_ABSOLUTE           41
            >>   36 POP_TOP             
                 37 JUMP_FORWARD             1 (to 41)
            >>   40 POP_TOP             
            >>   41 LOAD_CONST               0 (None)
                 44 RETURN_VALUE        
    

    So as you can see, at python bytecode level, both statements are same - even while you use single if at first statement, it will do JUMP_IF_FALSE after first comparison.

提交回复
热议问题