Skip to content

nested-loop-equijoin (OPT113)

Family: Complexity Rewrites (OPT) · Exact · Enabled by default · Severity warning (slower code) · No automatic fix

Size-dependent nested-loop equi-join (for a in A: for b in B: if a.k == b.k) -> dict index.

What it does

Checks nested loops that join two collections by comparing a key of each with ==: for a in A: for b in B: if a.k == b.k:, including a comprehension as the inner loop ([b for b in B if b.k == a.k]).

The keys are the loop elements themselves, their unpacked components (for k, v in pairs), attributes (a.k, a.x.y), and constant subscripts (a["k"], a[0]). Both loops must be for loops whose size depends on the data. The rule reports one diagnostic per inner loop, at its first matching comparison. It does not report:

  • traversals, where the inner iterable is computed from the outer element (for b in a.children, for b in index[a.k], for b in f(a), for b in xs[i + 1:]);
  • comparisons that do not select pairs: !=, a negated ==, one alternative of an or (a.k == b.k or match(a, b)), a result that is stored instead of tested, a value picked for every pair (1 if a.k == b.k else 0), a match that only skips to the next iteration (if a == b: continue in an all-pairs loop), or a comparison whose false side does work: an else / elif body, the failure of an assert a == b, a break / return on a mismatch, or statements that only the mismatches run because a match breaks. They run for the pairs an index would skip, so every pair is needed. Statements after the if that every pair runs do not stop a report, but it is then heuristic (below);
  • joins where the code fixes the size of either loop, so that the cost grows with one side only: a display of at most 16 items (for b in ("x", "y"), also through a name or a module constant of this or another module (NAME, module.NAME, also read in a module body) when nothing grows it, a comprehension over one ([r for r in ("a", "b") if r in seen]), and through enumerate / zip / sorted / .items() ...), range of integer constants with at most 16 steps (range(10), range(LIMIT)), and an iterable a length test on every path caps (if len(groups) > 8: raise ...).

What a report states

A report of the rule's exact tier states that, for each item of the outer loop, the inner loop compares a key of the outer item with a key of the inner item and does nothing else for an inner item that does not match. Its message says so: "for each item of orders, the loop over customers compares order.customer_id == customer.id and does nothing else for an item that does not match".

Its premises:

  • Equality of keys: the comparison is == between keys of the two items (the items, their components, attributes, or constant subscripts). Established. Each key that the inner loop loads runs no code of the project: an attribute is a plain one of an item whose class heki knows (a dataclass, attrs, or NamedTuple field, a slot, or what the class body or a method stores, with no property, method, other descriptor, __getattr__, or __getattribute__ of that name along the class's MRO or in a project subclass, every base a project class, and no metaclass heki does not know), and a subscript reads a builtin container or a component of a tuple the inner loop's builtin step makes. An attribute of an item of unknown class may be a property, so the report is then heuristic.
  • Steps through inputs: each loop steps through items of the function's inputs: every source of its items is a parameter, or an attribute or an item of one (orders, req.rows, sorted(customers)), also through a list the function fills only by appending items of such a source (for row in rows: results.append((key, row))). A call's result, a method's receiver (self.rows), a module constant, or a display leaves it open.
  • Idle on a mismatch: an inner item whose key differs runs only the loads of the two keys and the comparison: no statement before the test or after the if, no else or elif, no earlier and operand (b.active and a.k == b.k), and no code of the project to advance the inner loop. The inner iterable is a builtin container by its type (customers: list[Customer]; an annotation counts, assumption R2, unless a project subclass of the container defines its own __iter__), a display, sorted(...) or another builtin that builds a container, a view of a dict, or the pieces of a str (with the same condition on items and split). A value of unknown type may be a generator, and a generator, map, filter, or another call runs code for each item.
  • Same collection, same keys: the inner loop steps through the same collection on every iteration of the outer loop: its iterable is bound before the outer loop, or computed inside it only from values bound before it, and the outer loop does not change those values through their names, every name a copy binds to them (rows = ys makes ys one): no changing method, store, del, call that receives one (a builtin counts too when it is handed a function, as sorted(ys, key=f) is; a method of a builtin container only stores or reads its arguments), closure that captures one, yield, or await. Nor does it change the compared key of an inner item: no store into or deletion of what the key loads (b.k = ... for the key b.k), and no such call or closure that reaches the item or the key's object.

Not part of the claim: any count or size. A loop whose trip count the code fixes or caps (a constant range, a constant slice, a display, or a length test every path to the loop passes, if len(rows) > 100: raise ...) has no report in the exact tier: one of 16 or fewer is not reported at all, and a larger one is no evidence either way.

A report without one of these premises is heuristic, and its message says only "nested loops join orders and customers on order.customer_id == customer.id". It rests on the open premise that both loops are data-sized: the code does not fix the size of either loop at 16 or fewer, and a size heki cannot bound counts as data-sized.

No message claims a size or a cost. The help names a set or a dict only for keys known to be hashable, and an index built before the outer loop only for an inner collection that is the same, with the same keys, on every outer iteration; otherwise it states the condition ("if the keys are hashable, ..."). For a mapping the inner loop steps through by its own keys (for k, v in d.items() with the key k), it says to look each outer key up in the mapping instead.

Why is this bad?

The inner loop runs completely for every outer element, so the join costs O(n·m) comparisons. Indexing the inner collection by its key once (a dict from key to elements, or a set of the keys) makes it O(n + m). A break after the first match does not help much: a missing key still scans the whole inner collection.

Example

def attach(orders, customers):
    for order in orders:
        for customer in customers:
            if order.customer_id == customer.id:
                order.customer = customer
                break

Use instead:

def attach(orders, customers):
    by_id = {}
    for customer in customers:
        by_id.setdefault(customer.id, customer)  # the first match, as the `break`
    for order in orders:
        customer = by_id.get(order.customer_id)
        if customer is not None:
            order.customer = customer

The advice follows how the matches are used. When a match leaves the inner loop (break, return, raise), one element per key is enough: a set of the elements, or a dict from the key to its first element, as above. When every match is used (out.append((a, b)) for each equal pair), a set or a one-element dict would drop the repeated matches, so the help advises a dict from each key (or value) to the list of its elements. Each outer key then reads its list with .get(key, []): a loop over the index instead would drop the outer keys that match no element, which the nested loops give an empty list.

The keys must be hashable, and == must agree with their hash. When a key is known to be a list, dict, set, or bytearray (from its annotation, or as an element of a display of such displays), the help advises indexing a hashable form of it instead (a tuple or frozenset of its items).

Fix safety

No automatic fix.