Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of ternary operator vs if-else statement

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.

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

like image 858
Isaac Saffold Avatar asked Mar 09 '23 20:03

Isaac Saffold


1 Answers

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.

like image 132
Ned Batchelder Avatar answered Mar 27 '23 00:03

Ned Batchelder