Skip to main content

SKY-P403 · Quality, structure and performance

Nested loop that searches a collection per item

Low

The catalog gives no severity. Every finding is reported LOW.

A loop inside a loop that walks a whole collection to find the match for each outer item does work proportional to both sizes multiplied. SKY-P403 reports such an inner loop. The catalog lists the rule as "Suspicious performance pattern".

Languages
Python
Quality gate
counted toward the gate limits (full and diff scans). Advice that is measured on every --quality scan but not listed by default. It is listed, and counted toward max_quality, with --all-advice or when the rule is named in [tool.skylos.gate] rules.
Finding type
advice
Catalog name
Suspicious performance pattern
Wrong result? Report itA false positive, a missed case or a confusing message: it goes privately to the founder.

Why it matters

Matching 10,000 orders against 10,000 customers this way is 100 million comparisons. It is instant in a test with ten rows and takes minutes in production; a dictionary lookup does the same job in one pass.

What Skylos flags

app/reports/join.py · PythonReported on line 6
"""Join orders to their customers for the nightly report."""  def attach_customers(orders, customers):    for order in orders:        for customer in customers:            if customer.id == order.customer_id:                order.customer = customer    return orders

What Skylos leaves alone

app/reports/grid.py · Python
"""Plain-text grid for the stock report."""  def render_grid(rows):    lines = []    for row in rows:        cells = []        for cell in row:            cells.append(str(cell).rjust(8))        lines.append(" ".join(cells))    return "\n".join(lines)

Why Skylos leaves it alone

The inner loop walks the cells of the current row, a different part of the data on each pass. Every cell is visited once, so the work grows with the size of the grid, not with rows times rows.

How Skylos decides

  1. Runs with --quality, on Python for loops. For each outer loop it looks for for loops in its body, including inside if, with and try blocks, and through an inner loop with a fixed count.
  2. Skips the pair when either loop has a fixed number of passes (such as range(3) or a literal list), when the inner loop walks a part of the outer item, consumes an iterator shared with the outer loop, always ends with break or return, or runs only once before the outer loop is left.
  3. Reports only when the inner loop searches for the outer item: a test in its body (or in a filter lambda or generator condition) relates a value of the inner item to a value of the outer item, and the inner collection can be walked again on every pass.
  4. Reports LOW on the line of the inner for, naming both iterables.

How to fix it

Build a dictionary (or set) of the inner collection once, keyed by what you search for, and look each outer item up in it.

app/reports/join.py · Python · the fix, against the flagged file
"""Join orders to their customers for the nightly report."""  def attach_customers(orders, customers):Added:     by_id = {customer.id: customer for customer in customers}    for order in orders:Removed:         for customer in customers:Removed:             if customer.id == order.customer_id:Removed:                 order.customer = customerAdded:         order.customer = by_id.get(order.customer_id)    return orders

When it can be wrong

  • When both collections are small by design, for example a few configured regions per request, the nested search is reported although it costs nothing.
  • A search written as a comprehension or with any(...) inside the outer loop is not a for statement and is not reported.

Seeing a case that isn't listed here? Report the wrong result so the rule can be fixed. Don't paste company code: describe the shape of it.

How to silence it

  • On the inner for line (the reported line):

    Python
    for customer in customers:  # skylos: ignore[SKY-P403] at most 20 customers per batch
  • [tool.skylos] ignore = ["SKY-P403"] turns the rule off for the project. A baseline accepts existing findings, but it records the absolute file path and the line, so an entry stops matching when the checkout moves or the line shifts.

From the Skylos rule handbook, Skylos 5.8.0 (commit 5b880b0). All rules.