Sub topic 12
Performance and resource use
This chapter assumes you can read a diff, write basic unit tests, and run Python code. It follows the chapter on finding edge cases. Correct code can still be slow or wasteful. AI assistants often produce code that works on the three-row example in your prompt and fails at scale.
Why AI code drifts toward waste
An assistant optimizes for code that looks right and passes the example it was shown. It rarely knows your data sizes, your latency budget, or how often a function is called. So it picks the most familiar pattern, not the cheapest one. Your job in review is to ask: how does this behave when the input is 1,000 times larger?
What to look for in a diff
- Nested loops over the same data. A list lookup inside a loop is a hidden second loop.
- Queries inside loops. One database or HTTP call per item (the "N+1" pattern) turns 1 request into N+1.
- Loading everything into memory. Calls like
read()orfetchall()on unbounded data. - Repeated work. The same file read, regex compile, or computation inside a hot path.
- Missing limits. No timeout on a network call, no cap on retries, no pagination.
- Resources never released. Files, connections, or threads opened without a
withblock or a close.
A worked example
Suppose you asked for a function that returns the users who appear in both lists. The assistant writes this:
def common_users(a, b):
result = []
for user in a:
if user in b:
result.append(user)
return resultIt is correct. But user in b scans the whole list b each time. With n items in each list, the work grows with n², roughly 1,000,000 comparisons for 1,000 users and 100 million for 10,000. Converting b to a set makes each lookup constant time on average:
def common_users(a, b):
b_set = set(b)
return [user for user in a if user in b_set]The set version keeps the order of a, so the behavior is the same. This only works if the items are hashable, which is a correctness check you must also make.
Measure before you rewrite
Do not guess. Time the change with real-sized data.
import timeit
a = list(range(5000))
b = list(range(2500, 7500))
def slow(a, b):
return [u for u in a if u in b]
def fast(a, b):
b_set = set(b)
return [u for u in a if u in b_set]
print("list:", timeit.timeit(lambda: slow(a, b), number=3))
print("set: ", timeit.timeit(lambda: fast(a, b), number=3))Run it and compare. If the input will never exceed 20 items, the simpler version may be the better choice.
Balance cost and clarity
Not every inefficiency matters. Rewriting a loop that runs once at startup wastes review time and can make the code harder to read. Prioritize code that runs per request, per row, or inside a loop over user-controlled input. Also treat unbounded growth as a security issue: a missing size limit can let one request exhaust memory.
Quick review prompts
| Question | Red flag |
|---|---|
| What is the largest realistic input? | Code only tried with tiny samples |
| How many I/O calls per item? | A call inside a loop |
| Is memory bounded? | `fetchall()` or `read()` on unknown size |
| Are resources closed? | `open()` without `with` |
| Is there a timeout? | Network call with no limit |
Exercise
An assistant wrote a function that, for each order in a list of 500 orders, runs a separate SQL query to fetch the customer. Name the pattern, say why it is a problem, and suggest a fix.
Show answer
This is the N+1 query pattern: one query for the orders plus one per order. Each query adds network and database overhead, so latency grows with the number of orders. Fix it by fetching all needed customers in one query, for example with a JOIN or a WHERE id IN (...) clause, or by loading them into a dictionary keyed by id. Then measure to confirm the gain.
Exercise
A function calls rows = cursor.fetchall() on a table that could hold 50 million rows. What is the risk, and what would you ask the assistant to change?
Show answer
The risk is loading every row into memory at once, which can exhaust memory and crash the process. Ask for iteration in batches, for example fetchmany(1000) in a loop or a streaming cursor, and for a limit or pagination if the caller does not need all rows.