Python == with or vs. 在列表比较中 [英] Python == with or vs. in list comparison

查看:44
本文介绍了Python == with or vs. 在列表比较中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在检查相等性时,以下各项的速度和功能之间是否存在实际差异:

When checking for equality, is there any actual difference between speed and functionality of the following:

number = 'one'
if number == 'one' or number == 'two':

对比

number = 'one'
if number in ['one', 'two']:

推荐答案

如果值是文字常量(如本例),in 可能运行得更快,因为(非常有限)优化器将其转换为一次加载的常量 tuple,将执行的字节码工作减少到两次廉价加载,以及单个比较操作/条件跳转,其中链接 ors 涉及两个廉价的负载和每个测试的比较操作/条件跳转.

If the values are literal constants (as in this case), in is likely to run faster, as the (extremely limited) optimizer converts it to a constant tuple which is loaded all at once, reducing the bytecode work performed to two cheap loads, and a single comparison operation/conditional jump, where chained ors involve two cheap loads and a comparison op/conditional jump for each test.

对于两个值,它可能没有多大帮助,但随着值数量的增加,与替代方案相比节省的字节码(特别是如果命中不常见,或者在选项中均匀分布)可能是有意义的.

For two values, it might not help as much, but as the number of values increases, the byte code savings over the alternative (especially if hits are uncommon, or evenly distributed across the options) can be meaningful.

以上特别适用于CPython参考解释器;其他解释器可能具有较低的每字节码成本,从而减少或消除性能差异.

The above applies specifically to the CPython reference interpreter; other interpreters may have lower per-bytecode costs that reduce or eliminate the differences in performance.

如果number 是一个更复杂的表达式,则具有普遍优势;my_expensive_function() in (...) 显然会优于 my_expensive_function() == A 或 my_expensive_function() == B,因为前者只计算一次值.

A general advantage comes in if number is a more complicated expression; my_expensive_function() in (...) will obviously outperform my_expensive_function() == A or my_expensive_function() == B, since the former only computes the value once.

也就是说,如果 tuple 中的值不是常量文字,特别是如果命中对早期值很常见,in 通常会更昂贵(因为它每次都必须创建用于测试的序列,即使它最终只测试了第一个值).

That said, if the values in the tuple aren't constant literals, especially if hits will be common on the earlier values, in will usually be more expensive (because it must create the sequence for testing every time, even if it ends up only testing the first value).

这篇关于Python == with or vs. 在列表比较中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆