Python 中 and 与多个 if 的效率

发布于 2024-09-15 07:11:35 字数 282 浏览 4 评论 0原文

在 if 语句中使用 and 与使用多个 if 语句在效率上有区别吗?换句话说,

if expr1 == expr2 and expr3==expr4:
  dostuff()

从效率的角度来看,有什么不同吗:

if expr1 == expr2:
  if expr3 == expr4:
    dostuff()

我非常基本的测试并没有揭示出差异,但是具有更多知识(或至少更彻底的测试)的人是否有明确的答案?

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 expr3==expr4:
  dostuff()

different from an efficiency standpoint then:

if expr1 == expr2:
  if expr3 == expr4:
    dostuff()

My very basic testing does not reveal a difference, but does someone with more knowledge (or at least more thorough testing) have a definitive answer?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

瞳孔里扚悲伤 2024-09-22 07:11:35

使用 and 和嵌套 if 之间的速度差异很小。你找错了树。考虑这棵树:

if oftenTrueCondition and rarelyTrueCondition:

if rarelyTrueCondition and oftenTrueCondition:

So 相比,除非必须首先评估第一个条件(它是阻止下一个表达式崩溃或做一些愚蠢/昂贵的事情的保护),请考虑交换评估顺序。

Any differences in speed between using and and nested ifs will be minimal. You are barking up the wrong tree. Consider this tree:

if oftenTrueCondition and rarelyTrueCondition:

compared with

if rarelyTrueCondition and oftenTrueCondition:

So, unless the first condition must be evaluated first (it is a guard to stop the next expression from crashing or doing something silly/expensive), consider swapping the order of evaluation.

拿命拼未来 2024-09-22 07:11:35

这不足以影响您的决定(如果有的话)。 IMO,这里的决定应该纯粹从可读性的角度做出。我认为第一个通常更标准,但在某些情况下第二个可能更清晰。选择最能传达您意图的方法。

This isn't enough of a performance difference, if any, to affect your decision. IMO, the decision here should be made purely from a readability perspective. The first is generally more standard, I think, but there are situations when the second might be clearer. Choose the method that best gets your intent across.

放手` 2024-09-22 07:11:35

无论哪种情况,ifexpr1 == expr2 的计算结果为 false,第二个值将不会被计算。

In either case, expr1 == expr2 evaluates to false in if, the second will not be evaluated.

还不是爱你 2024-09-22 07:11:35

如有疑问,您可以使用 dis 模块检查 python 编译语句的内容:

>>> 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        

因此,如您所见,在 python 字节码级别,两个语句是相同的 - 即使您在第一个语句中使用单个 if ,它也会在之后执行 JUMP_IF_FALSE首先比较。

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.

贱贱哒 2024-09-22 07:11:35

第一个(一个 ifand)更快:-)

我使用 timeit 进行了尝试。结果如下:

Variant 1: 9.82836714316
Variant 2: 9.83886494559
Variant 1 (True): 9.66493159804
Variant 2 (True): 10.0392633241

对于最后两个比较,第一个比较为 True,因此跳过第二个比较。有趣的结果。


import timeit


print "Variant 1: %s" % timeit.timeit("""
for i in xrange(1000):
    if i == 2*i and i == 3*i:
        pass
        """,
        number = 1000)

print "Variant 2: %s" % timeit.timeit("""
for i in xrange(1000):
    if i == 2*i:
        if i == 3*i:
            pass
        """,
        number = 1000)

print "Variant 1 (True): %s" % timeit.timeit("""
for i in xrange(1000):
    if i == i and i == 3*i:
        pass
        """,
        number = 1000)

print "Variant 2 (True): %s" % timeit.timeit("""
for i in xrange(1000):
    if i == i:
        if i == 3*i:
            pass
        """,
        number = 1000)

The first one (one if with and) is faster :-)

I tried it out using timeit. These are the results:

Variant 1: 9.82836714316
Variant 2: 9.83886494559
Variant 1 (True): 9.66493159804
Variant 2 (True): 10.0392633241

For the last two, the first comparision is True, so the second one is skipped. Interesting results.


import timeit


print "Variant 1: %s" % timeit.timeit("""
for i in xrange(1000):
    if i == 2*i and i == 3*i:
        pass
        """,
        number = 1000)

print "Variant 2: %s" % timeit.timeit("""
for i in xrange(1000):
    if i == 2*i:
        if i == 3*i:
            pass
        """,
        number = 1000)

print "Variant 1 (True): %s" % timeit.timeit("""
for i in xrange(1000):
    if i == i and i == 3*i:
        pass
        """,
        number = 1000)

print "Variant 2 (True): %s" % timeit.timeit("""
for i in xrange(1000):
    if i == i:
        if i == 3*i:
            pass
        """,
        number = 1000)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文