Question:
What is the difference between the following lines:
if not x == 'val':
Y
if x != 'val':
Is there a way to check if one is more efficient than the other?
or, maybe the following block would be better:
if x == 'val':
pass
else:
Answer:
disassembled
If we use the disassembler for Python ( dis
) , we see that all 3 compile to the same number of instructions, and only differ in the POP_JUMP_IF_TRUE
or POP_JUMP_IF_FALSE
!=
0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 ('val')
6 COMPARE_OP 3 (!=)
9 POP_JUMP_IF_FALSE 15
not ==
0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 ('val')
6 COMPARE_OP 2 (==)
9 POP_JUMP_IF_TRUE 15
== else
0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 ('val')
6 COMPARE_OP 2 (==)
9 POP_JUMP_IF_FALSE 15
profile
Using cProfile , we can measure the execution time and perform a benchmark :
ncalls tottime percall cumtime percall filename:lineno(function)
not == 5000000 1.589 0.000 1.589 0.000 ./prog.py:8(en)
== else 5000000 1.562 0.000 1.562 0.000 ./prog.py:12(ee)
!= 5000000 1.508 0.000 1.508 0.000 ./prog.py:4(ne)
Sorted from slowest to fastest, we can see that:
-
if not x == 'val'
is the slowest. -
if x == 'val'
+else
is ~ 1.7% faster. -
if x != 'val'
is ~ 3.6% even faster. - Between the slowest and the fastest we only save 81ms / 5 million comparisons.
* Or here is a more complex example to compare true and false cases with random strings.
conclusion
The if x != 'val'
condition is slightly more efficient.
However, in my opinion, the difference is not significant enough to change the style when coding. I absolutely prefer the code to be as easy to read as possible, and I would only think of taking this result into account in extremely intensive calculations that require saving every possible fraction of a second.