草庐IT

Python if not == vs if !=

coder 2023-04-28 原文

这两行代码有什么区别:

if not x == 'val':

if x != 'val':

一个比另一个更有效吗?

使用会更好

if x == 'val':
    pass
else:

最佳答案

使用 dis查看为两个版本生成的字节码:

不是==

  4           0 LOAD_FAST                0 (foo)
              3 LOAD_FAST                1 (bar)
              6 COMPARE_OP               2 (==)
              9 UNARY_NOT           
             10 RETURN_VALUE   

!=

  4           0 LOAD_FAST                0 (foo)
              3 LOAD_FAST                1 (bar)
              6 COMPARE_OP               3 (!=)
              9 RETURN_VALUE   

后者的操作较少,因此可能会稍微高效一些。


有人指出in the commments (谢谢, @Quincunx )你有 if foo != barif not foo == bar 的操作数完全相同,只是这样COMPARE_OP 改变并且 POP_JUMP_IF_TRUE 切换到 POP_JUMP_IF_FALSE:

不是==:

  2           0 LOAD_FAST                0 (foo)
              3 LOAD_FAST                1 (bar)
              6 COMPARE_OP               2 (==)
              9 POP_JUMP_IF_TRUE        16

!=

  2           0 LOAD_FAST                0 (foo)
              3 LOAD_FAST                1 (bar)
              6 COMPARE_OP               3 (!=)
              9 POP_JUMP_IF_FALSE       16

在这种情况下,除非每次比较所需的工作量有所不同,否则您根本不可能看到任何性能差异。


但是,请注意,两个版本在逻辑上并不总是相同,因为它取决于 __eq____ne__ 的实现对于有问题的对象。根据 the data model documentation :

There are no implied relationships among the comparison operators. The truth of x==y does not imply that x!=y is false.

例如:

>>> class Dummy(object):
    def __eq__(self, other):
        return True
    def __ne__(self, other):
        return True


>>> not Dummy() == Dummy()
False
>>> Dummy() != Dummy()
True

最后,也许也是最重要的:一般来说,如果两个 在逻辑上相同,x != ynot 更易读x == y.

关于Python if not == vs if !=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31026754/

有关Python if not == vs if !=的更多相关文章

随机推荐