Sub topic 12
Performance and Resource Use
This chapter assumes you can read a diff, write a basic unit test, and reason about loops and big-O notation at a working level. You should also have read the chapters on edge cases and tests as evidence. Performance review comes after correctness, because a fast wrong answer has no value.
Why performance needs its own pass
An AI assistant writes code that satisfies the prompt and passes the example you gave it. It rarely knows your data size, your traffic, or your memory limit. A function that is fine for 20 items can be unusable for 2 million. The code looks the same in both cases, so the problem only appears if you ask the right questions during review.
Performance problems from AI output tend to be ordinary ones:
- Work repeated inside a loop that could be done once.
- A data structure that makes lookups slow.
- A whole file or result set loaded into memory.
- One network or database call per item instead of one per batch.
- Resources opened and never released.
You do not need to profile every change. You need to decide whether the change sits on a path where these problems would matter, and then check that path.
Step 1: Decide whether performance matters here
Spend effort in proportion to risk. Ask three questions:
- How large can the input get in production, not in the example?
- How often does this code run? Once at startup, per request, or per record?
- What does it touch? Memory, disk, network, a database, or a shared lock?
A one-off migration script that runs on 500 rows needs little attention. A function called on every web request, or a loop over every row in a large table, needs a careful look.
Step 2: Look for accidental quadratic work
The most common issue is nested iteration hidden inside a convenient expression. Here is a typical AI-written function that removes duplicates while keeping order:
def unique_ids(ids):
result = []
for item in ids:
if item not in result:
result.append(item)
return resultThe item not in result check scans a list. Each check costs time proportional to the length of result, so the whole function is O(n²). With 1,000 items you will not notice. With 200,000 unique items it takes minutes.
The fix uses a set for membership checks, which take constant time on average:
def unique_ids(ids):
seen = set()
result = []
for item in ids:
if item not in seen:
seen.add(item)
result.append(item)
return resultThis version also assumes the items are hashable. That is a correctness condition worth checking against your data. If the items can be lists or dicts, the set approach raises TypeError.
When you read a diff, watch for these shapes:
| Pattern in the diff | Why it is slow | Usual fix |
|---|---|---|
| `x in some_list` inside a loop | Linear scan per check | Build a `set` or `dict` first |
| `list.insert(0, x)` or `list.pop(0)` in a loop | Shifts every element | Use `collections.deque` |
| String `+=` in a large loop | Can copy repeatedly | Collect parts and use `"".join(parts)` |
| Regex compiled inside a loop | Repeated setup cost | Compile once outside the loop |
| Sorting inside a loop | Repeated O(n log n) work | Sort once, or use `heapq` |
Step 3: Check for the N+1 query pattern
AI-generated data access code often fetches a list and then queries once per item. This is called the N+1 query problem: one query for the list, plus N queries for related data. Each query pays network and database overhead, so the cost grows with the list.
import sqlite3
def orders_with_totals_slow(conn: sqlite3.Connection, user_ids):
totals = {}
for user_id in user_ids:
row = conn.execute(
"SELECT COALESCE(SUM(amount), 0) FROM orders WHERE user_id = ?",
(user_id,),
).fetchone()
totals[user_id] = row[0]
return totalsThis issues one query per user. With a local SQLite file the cost is small. With a remote database at 2 ms per round trip, 10,000 users cost 20 seconds in latency alone.
A batched version uses a single query with a GROUP BY:
import sqlite3
def orders_with_totals(conn: sqlite3.Connection, user_ids):
user_ids = list(user_ids)
if not user_ids:
return {}
placeholders = ",".join("?" for _ in user_ids)
query = (
"SELECT user_id, SUM(amount) FROM orders "
f"WHERE user_id IN ({placeholders}) GROUP BY user_id"
)
rows = conn.execute(query, user_ids).fetchall()
totals = {user_id: 0 for user_id in user_ids}
totals.update({user_id: total for user_id, total in rows})
return totalsTwo review points apply here. First, the f-string builds only the placeholder list (?,?,?), never user values, so it stays safe from injection. Second, databases limit the number of parameters in one statement. SQLite's default limit is commonly 999 or 32,766 depending on version, so very large lists need chunking. Do not assume the AI handled that.
Step 4: Check memory use
Ask whether the code needs all the data at once. AI-written code often reads entire files into memory because it is the shortest way to write the function.
def count_error_lines_slow(path):
with open(path) as f:
lines = f.readlines()
return sum(1 for line in lines if "ERROR" in line)readlines() holds the whole file in memory. A 4 GB log file needs more than 4 GB of RAM. Iterating over the file object reads one line at a time:
def count_error_lines(path):
with open(path) as f:
return sum(1 for line in f if "ERROR" in line)The same idea applies to other places:
- Use generators or iterators instead of building a full list when you only loop once.
- Page through database results with a cursor or
LIMIT/OFFSETrather thanfetchall()on a large table. - Stream HTTP downloads instead of reading the full body into a variable.
- Check for caches that grow without bound, such as a module-level dict that gains an entry per request and never evicts any.
A cache with no size limit is a memory leak in practice. If the diff adds one, look for functools.lru_cache(maxsize=...) with a number, or an explicit expiry policy. Note that lru_cache(maxsize=None) is unbounded.
Step 5: Check resource cleanup
Files, sockets, database connections, and threads are limited. Code that opens them without guaranteed cleanup works in a demo and fails in a long-running service, where leaked handles eventually hit the operating system limit.
Look for these in the diff:
open()without awithblock.- Database connections created inside a function called per request, with no pooling or close.
- HTTP calls with no timeout. In the
requestslibrary, a call withouttimeout=can wait forever. - Retry loops with no limit and no delay, which can hammer a failing service.
- Threads or tasks started and never joined or cancelled.
A network call missing a timeout is a particularly common AI omission:
import requests
def fetch_status(url):
response = requests.get(url, timeout=5)
response.raise_for_status()
return response.status_codeThe timeout=5 argument is the line to look for. The raise_for_status() call makes HTTP errors visible instead of silently returning an error page as if it were data.
Step 6: Measure before you change anything
Reading finds suspects. Measurement confirms them. Before asking for a rewrite, get a number. Python's standard library includes timeit for small comparisons:
import timeit
setup = "ids = list(range(5000)) * 2"
slow = timeit.timeit(
"r = []\nfor i in ids:\n if i not in r:\n r.append(i)",
setup=setup,
number=3,
)
fast = timeit.timeit(
"s = set()\nr = []\nfor i in ids:\n if i not in s:\n s.add(i)\n r.append(i)",
setup=setup,
number=3,
)
print(f"list membership: {slow:.3f}s, set membership: {fast:.3f}s")Run it with sizes near your real data. The exact times depend on your machine, but the gap should grow quickly as the input grows. That growth is the evidence that the algorithm matters.
For whole programs, use a profiler such as cProfile to find where time actually goes. For memory, tracemalloc in the standard library shows which lines allocate the most.
Step 7: Turn findings into specific feedback
When you ask the assistant to revise, give it facts. "Make this faster" produces speculative rewrites. A better request names the problem and the constraint:
- "
unique_idsuses list membership inside a loop. Inputs can reach 500,000 items. Use a set and keep first-seen order." - "This reads the whole file. Files can exceed available memory. Process line by line."
Then re-run your measurement and your tests. A performance rewrite is a behavior change, so the tests from the earlier chapters must still pass. An optimization that changes ordering, drops duplicates differently, or alters error handling is a regression, not a win.
Common mistakes in this part of the review
- Optimizing without data. Rewriting code that takes 2 ms per call, called twice a day, wastes review time and adds risk.
- Trusting the example size. The prompt's sample had five rows. Production has five million.
- Accepting clever rewrites. A complex "optimized" version that nobody on the team can read costs more over time than the milliseconds it saves. Weigh it against the maintainability chapter.
- Ignoring tail behavior. Average speed can be fine while one slow input, such as a pathological regex match, takes down a service.
- Skipping limits. Unbounded retries, caches, queues, and thread pools fail only under load.
Exercise
A reviewer finds this in an AI-written diff: for order in orders: customer = db.query("SELECT * FROM customers WHERE id = ?", order.customer_id). The orders list can hold 20,000 entries and the database is on another host. Name the problem, give one fix, and say one thing you must still check about the fix.
Show answer
This is an N+1 query pattern: one query per order adds 20,000 network round trips. Fix it by collecting the distinct customer IDs and fetching them in one query (for example with WHERE id IN (...)), then looking customers up in a dict. You must still check the database's limit on parameters per statement and chunk the ID list if needed. You should also confirm with tests that orders with a missing customer are handled the same way as before.
Exercise
An assistant adds @lru_cache(maxsize=None) to a function that takes a user-supplied search string. Why is this a review concern, and what would you change?
Show answer
With maxsize=None the cache never evicts entries. Each distinct search string adds a permanent entry, so memory grows with traffic and users can inflate it deliberately. Set a bounded maxsize (for example 1024), or use a cache with expiry, and confirm the cached function is pure, meaning the same input always gives the same result.