Python 中 and 与多个 if 的效率
在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用
and
和嵌套 if 之间的速度差异很小。你找错了树。考虑这棵树:与
So 相比,除非必须首先评估第一个条件(它是阻止下一个表达式崩溃或做一些愚蠢/昂贵的事情的保护),请考虑交换评估顺序。
Any differences in speed between using
and
and nested ifs will be minimal. You are barking up the wrong tree. Consider this tree:compared with
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.
这不足以影响您的决定(如果有的话)。 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.
无论哪种情况,
if
中expr1 == expr2
的计算结果为false
,第二个值将不会被计算。In either case,
expr1 == expr2
evaluates tofalse
inif
, the second will not be evaluated.如有疑问,您可以使用 dis 模块检查 python 编译语句的内容:
因此,如您所见,在 python 字节码级别,两个语句是相同的 - 即使您在第一个语句中使用单个 if ,它也会在之后执行 JUMP_IF_FALSE首先比较。
When in doubt, you can check what does python compile your statements in, using dis module:
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.
第一个(一个
if
与and
)更快:-)我使用
timeit
进行了尝试。结果如下:对于最后两个比较,第一个比较为
True
,因此跳过第二个比较。有趣的结果。The first one (one
if
withand
) is faster :-)I tried it out using
timeit
. These are the results:For the last two, the first comparision is
True
, so the second one is skipped. Interesting results.