Code review for efficiency
Reading someone else's code with cost in mind: the six-point checklist, the level of a remark (blocking, suggestion, taste) and how to word it.
- 20 cards
- 5 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
- Understand
A few cards from the deck
Code review: what is it?
Show the answer
Reading of a change by someone other than its author, before it is merged into the shared code.
It catches what the author no longer sees: logic, readability and cost defects. On the efficiency side, you look for what will become slow when the data grows.
What do you flag in this function called with two lists of 100,000 items, and what is the fix?
```python
def communs(a, b):
resultat = []
for x in a:
if x in b:
resultat.append(x)
return resultat`x in bscans a list, O(n × m); turnbinto aset- The
forloop is slow in Python; replace it with awhileloop or withmap appendcopies the list on every call; preallocateresultat- Sort
abefore the loop so the lookups are faster
Show the answer
x in bscans a list, O(n × m); turnbinto asetEach
x in bcompares with every element of the list: up to 10¹⁰ comparisons here. Asetfinds an element in constant time on average, and the cost becomes O(n + m).appendis amortised O(1), and sortingadoes nothing for searchingb.The checklist on the efficiency side: hidden complexity, … data structure, … work, allocations in a loop, input/output in a loop, … edge case.
Show the answer
The checklist on the efficiency side: hidden complexity, unsuitable data structure, repeated work, allocations in a loop, input/output in a loop, size edge case.
The six points are mostly spotted around loops: an expensive operation inside a loop is multiplied by the number of iterations.
Code smell: what is it?
Show the answer
A sign, in the structure of a piece of code, of a probable design problem, without being a bug as such.
A 200-line function or a query inside a loop does not crash: they cost later. They are flagged so they get fixed before they become an incident.
The diff adds, inside a loop over the orders, one
SELECT * FROM lignes WHERE commande_id = ?per order. What fix do you ask for?- A single query, with a join or
IN - Add an index on
commande_idand keep the loop as it is - Run the loop's queries in parallel
- Replace
SELECT *with the list of columns used
Show the answer
A single query, with a join or
INThe index speeds up each query but leaves N round trips; parallelising spreads them without removing them; listing the columns is good practice, but unrelated to the number of queries. Only a grouped query brings the cost from N+1 down to 1.
- A single query, with a join or