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

I was wondering which code is faster? For example, we have a variable x:

if x!=0 : return

or

if x: return

I tried checking with timeit, and here are the results:

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

I can’t figure it out.

+4
source share
1 answer

This is too difficult to show in a comment: there is more (or less ;-)) than any of the comments that have been noted so far. With a()and b(), as defined by you, release:

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

What happens when the CPython compiler sees if 0:or if 1:, it evaluates them at compile time and does not generate any code for testing at run time. Thus, the code for b()simply loads Noneand returns it.

, a(), :

>>> 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

- . a() .

, @Charles Duffy: - Python. , :-), dis.dis, , .

+15

All Articles