三元运算符与if-else语句的性能 [英] Performance of ternary operator vs if-else statement

查看:85
本文介绍了三元运算符与if-else语句的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:的确,许多其他语言都回答了这个问题.但是,我找不到Python的答案,因此请不要将其标记为重复.

Note: It's true that this question has been answered for many other languages. However, I could not find an answer for Python, so do not mark as duplicate.

if-else语句和Python中的三元运算符之间在性能上有区别吗?

Is there a difference in performance between the if-else statement and the ternary operator in Python?

推荐答案

我怀疑是否存在性能差异.它们编译为等效的字节码序列:

I doubt there is a performance difference. They compile to equivalent sequences of bytecodes:

>>> def f():
...   return a if b else c
...
>>> dis.dis(f)
  2           0 LOAD_GLOBAL              0 (b)
              2 POP_JUMP_IF_FALSE        8
              4 LOAD_GLOBAL              1 (a)
              6 RETURN_VALUE
        >>    8 LOAD_GLOBAL              2 (c)
             10 RETURN_VALUE
>>> def g():
...   if b:
...     return a
...   else:
...     return c
...
>>> dis.dis(g)
  2           0 LOAD_GLOBAL              0 (b)
              2 POP_JUMP_IF_FALSE        8

  3           4 LOAD_GLOBAL              1 (a)
              6 RETURN_VALUE

  5     >>    8 LOAD_GLOBAL              2 (c)
             10 RETURN_VALUE
             12 LOAD_CONST               0 (None)
             14 RETURN_VALUE

与大多数性能问题一样,答案是要衡量.

As with most performance questions, the answer is to measure.

这篇关于三元运算符与if-else语句的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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