Python if not == vs if !=

后端 未结 7 1391
轻奢々
轻奢々 2020-12-07 08:09

What is the difference between these two lines of code:

if not x == \'val\':

and

if x != \'val\':

Is one

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 08:32

    >>> from dis import dis
    >>> dis(compile('not 10 == 20', '', 'exec'))
      1           0 LOAD_CONST               0 (10)
                  3 LOAD_CONST               1 (20)
                  6 COMPARE_OP               2 (==)
                  9 UNARY_NOT
                 10 POP_TOP
                 11 LOAD_CONST               2 (None)
                 14 RETURN_VALUE
    >>> dis(compile('10 != 20', '', 'exec'))
      1           0 LOAD_CONST               0 (10)
                  3 LOAD_CONST               1 (20)
                  6 COMPARE_OP               3 (!=)
                  9 POP_TOP
                 10 LOAD_CONST               2 (None)
                 13 RETURN_VALUE
    

    Here you can see that not x == y has one more instruction than x != y. So the performance difference will be very small in most cases unless you are doing millions of comparisons and even then this will likely not be the cause of a bottleneck.

提交回复
热议问题