3

I ran the code

a = True
b = False
c = False
d = False
e = False
import time
iterations = int(1e6)
start = time.time()
for _ in range(iterations):
    a or b or c or d or e
print(time.time() - start)
start = time.time()
for _ in range(iterations):
    b or c or d or e or a
print(time.time() - start)

Results

0.10876178741455078
0.26296424865722656
  • Why does the order of boolean evaluation make a difference in speed?
  • Is it because of some form of optimization?
  • If so is there a resource I can read?
arjoonn
  • 960
  • 1
  • 9
  • 20

2 Answers2

7

This is because of short-circuiting:

True or WHATEVER # always True

In the first expression a which is True comes first and there is no need to proceed.

A cool way to show this is using an piece of code that is never run because of short-circuiting:

>>> def _print():
...     print "no short circuit"
...
>>> True or _print()
True
>>> False or _print()
no short circuit
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
2

Because or evaluates lazily, and if it finds True there are no more checks needed; while if the first one is False then it has to evaluate the next expression until True is found or there no more checks.

GergelyPolonkai
  • 6,230
  • 6
  • 35
  • 69
Lipis
  • 21,388
  • 20
  • 94
  • 121