Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is faster, `if x` or `if x != 0`?

Tags:

python

I was wondering, what code runs faster? For example, we have variable x:

if x!=0 : return

or

if x: return

I tried to check with timeit, and here are results:

 >>> def a():
...     if 0 == 0: return
...
>>> def b():
...     if 0: return
...>>> timeit(a)
0.18059834650234943
>>> timeit(b)
0.13115053638194007
>>>

I can't quite understand it.

like image 235
Disciples Avatar asked Dec 04 '22 00:12

Disciples


1 Answers

This is too hard to show in a comment: there's more (or less ;-) ) going on here than any of the comments so far noted. With a() and b() defined as you showed, let's go on:

>>> from dis import dis
>>> dis(b)
  2           0 LOAD_CONST               0 (None)
              3 RETURN_VALUE

What happens is that when the CPython compiler sees if 0: or if 1:, it evaluates them at compile time, and doesn't generate any code to do the testing at run time. So the code for b() just loads None and returns it.

But the code generated for a() is much more involved:

>>> dis(a)
  2           0 LOAD_CONST               1 (0)
              3 LOAD_CONST               1 (0)
              6 COMPARE_OP               2 (==)
              9 POP_JUMP_IF_FALSE       16
             12 LOAD_CONST               0 (None)
             15 RETURN_VALUE
        >>   16 LOAD_CONST               0 (None)
             19 RETURN_VALUE

Nothing is evaluated at compile time in this case - it's all done at run time. That's why a() is much slower.

Beyond that, I endorse @Charles Duffy's comment: worrying about micro-optimization is usually counterproductive in Python. But, if you must ;-) , learn how to use dis.dis so you're not fooled by gross differences in generated code, as happened in this specific case.

like image 165
Tim Peters Avatar answered Dec 06 '22 14:12

Tim Peters