Pavlos Kallis

Improving performance of OR statements in Python

Published at April 8, 2022, 6:27 p.m.

When you have an expression a() OR b() in python, if a() is a lot slower than b(), it is better

to change the condition to b() OR a(). The statement is exactly the same as a() or b() is always equal to b() or a().

 

import time


def a_slow_function():
  time.sleep(2)
  print("A slow function complete")


def a_fast_function():
  time.sleep(0.1)
  print("A fast function complete")


start = time.time()

a_fast_function() or a_slow_function()

print("Time:", time.time() - start)

a_slow_function() or a_fast_function()

print("Time:", time.time() - start)