Topic 2 of 5 · 5 min read
Hidden quadratic loops in generated code
Goal: Estimate the time complexity of an AI-written function and rewrite the hot path to remove a hidden quadratic step.
A hidden quadratic loop is a loop that contains another scan, so doubling the input quadruples the time; find it by asking what each line costs, not just how many lines there are. AI code often hides the inner scan inside a single innocent-looking call.
Check yourself · 1 of 3
A function loops over n items and calls list.index on a list of n items inside the loop. What is its time complexity?
Why it matters
Quadratic code is fast on the 20 rows in a unit test and painful at 50,000 rows. At 50,000 items, an n x n step is 2.5 billion operations. The function is correct, reads well and passes review, then times out in production. Assistants write it because the simplest way to say "for each A, find the matching B" is a loop with a lookup inside.
Where the hidden scan lives
x in listinside a loop. Membership in a list scans the list; in a set or dict it is close to constant time. The Python wiki's TimeComplexity page lists these costs.list.index,list.remove,array.includes,array.find,indexOfinside a loop.- Sorting inside a loop when one sort before the loop would do.
- String concatenation in a loop that copies the whole string each time in some languages.
- Spread or copy per iteration, such as
acc = [...acc, item]in areduce. - Repeated filters over the same array for each key.
How to review it
- Name the input size,
n. - For each loop, write the cost of one pass of its body. A call you do not recognise gets looked up.
- Multiply. A loop of
nwith a body ofnisn^2. - Check the size that really occurs. A quadratic step on 30 items is fine.
Before and after
# Weak: O(n * m). "in" scans the whole list each time.
def new_users(incoming, existing_ids):
return [u for u in incoming if u["id"] not in existing_ids] # existing_ids is a list
# Fixed: build a set once, then each check is about O(1).
def new_users(incoming, existing_ids):
seen = set(existing_ids)
return [u for u in incoming if u["id"] not in seen]
What goes wrong
- Trusting small tests. Always try a 10x and 100x input.
- Optimising a loop that runs on 10 items. Fix the step that scales.
- Trading memory for speed blindly. A set or index uses extra memory; that is usually a good trade, but say so.
Examples
Spread inside reduce
// Weak: copies the accumulator on every item, O(n^2)
const byId = items.reduce((acc, it) => ({ ...acc, [it.id]: it }), {});
// Fixed: mutate one object, O(n)
const byId = {};
for (const it of items) byId[it.id] = it;
With 100,000 items the first version copies billions of properties in total.
Matching two lists
An agent writes a script that, for each of 40,000 customers, runs next(o for o in orders if o.customer_id == c.id) over 200,000 orders. That is up to 8 billion comparisons. Group the orders by customer id into a dict first, then look each customer up directly.
Key points
- Time complexity is about how cost grows with input size, so always name n and test with a much larger n.
- The inner scan is usually hidden in one call such as in on a list, indexOf, find or a spread inside reduce.
- Build a set, dict or index once before the loop to turn repeated scans into near-constant lookups.
- Sort once outside a loop rather than sorting inside it.
- Only fix a quadratic step that runs on large inputs; a nested loop over 20 items is fine.
Common mistakes
- Passing review because the code is correct on a small fixture.
- Counting lines of code instead of the cost of each call inside the loop.
- Using a list for membership checks because it was the first structure that came to mind.
- Optimising a nested loop over a tiny collection while missing the scan that scales.
Check yourself · 2 of 3
Why do quadratic functions often pass tests but fail in production?
Check yourself · 3 of 3
An AI function checks if email in seen_emails for each of 100,000 rows, where seen_emails is a list. What is the best fix?
Practice items, not counted towards your mastery.
Start here
- Use The Index, Luke: SQL indexing and tuning (opens in a new tab)BookFree
A free book on how indexes and query shape decide database speed.
- Using EXPLAIN (PostgreSQL documentation) (opens in a new tab)DocsFree
How to read a query plan, with estimated and actual costs.
- Flame Graphs (Brendan Gregg) (opens in a new tab)ArticleFree
The inventor explains how to read a flame graph to find where time goes.
More for this topic
- TimeComplexity (Python wiki) (opens in a new tab)DocsFree
Big-O costs of list, set and dict operations, so you can see which ones hide a scan.