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.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios
  5. 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 b scans a list, O(n × m); turn b into a set
    • The for loop is slow in Python; replace it with a while loop or with map
    • append copies the list on every call; preallocate resultat
    • Sort a before the loop so the lookups are faster
    Show the answer

    x in b scans a list, O(n × m); turn b into a set

    Each x in b compares with every element of the list: up to 10¹⁰ comparisons here. A set finds an element in constant time on average, and the cost becomes O(n + m). append is amortised O(1), and sorting a does nothing for searching b.

  • 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_id and 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 IN

    The 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.