On-screen text
Make your
slow code
run faster
SWIPE
0) Move database
queries out of loops
query = "SELECT * FROM users WHERE id = ?"
for user_id in user_ids:
user = db.query(query, user_id)
process(user)
query = "SELECT * FROM users WHERE id IN (?)"
users = db.query(query, user_ids)
for user in users:
process(user)
1) Get rid of your
nested loops
def find_common(a, b): # O(n^2)
common = []
for x in a:
for y in b:
if x == y:
common.append(x)
return common
def find_common(a, b): # O(n)
set_b = set(b)
return [x for x in a if x in set_b]
2) Use the right
data structure
# Using a list
participants = ["dave", "eva", "frank"]
# Linear search through the list
if "eva" in participants:
print("Match found")
# Using a set
participants = {"dave", "eva", "frank"}
# Constant-time check via hash table
if "eva" in participants:
print("Match found")
3) Cut unnecessary
logging and I/O
for item in items:
with open("log.txt", "a") as f:
f.write(f"{item}\n")
buffer = [f"{item}\n" for item in items]
with open("log.txt", "a") as f:
f.writelines(buffer)
4) Always prefer
built-in functions
total = 0
for x in numbers:
total += x
# Faster, C-optimized
total = sum(numbers)
Save this post for
the next time your
code runs slow!