loop-invariant-container-rebuild (OPT130)¶
Family: Complexity Rewrites (OPT) · Exact · Opt-in · Severity warning (slower code) · Proven-safe suggestion (--fix --include-size-dependent)
Opt-in: size-dependent loop-invariant container reconstruction (e in set(keys)).
What it does¶
Checks loops that rebuild the same container on every iteration just to test membership,
e in set(keys) (also list(...), tuple(...), dict(...)), and suggests building it once
before the loop.
Opt-in and size-dependent: it runs when extend-select names it or with
--include-size-dependent, which also applies its proven rewrites with --fix.
What a report states¶
A report states that a builtin constructor (set(keys), list(...), tuple(...), dict(...)),
in a loop, builds a new container for a membership test each time it runs.
Its premises:
- Builtin type by construction: the constructor builds a builtin container of a known type.
Established: heki reports only a call of the builtin constructor. What it builds the container
from may be of an unknown type, which blocks the rewrite (
ZeroTripExceptionSafe): "Rewrite proven safe" is then open. - In a loop: the statement is in the body of a loop. Established by the IR.
- Rewrite proven safe: the help says
[safe fix: ...],[proven-safe suggestion: ...], or[proven safe; ...]. A report whose help names a blocking obligation instead ([not auto-fixable: ...]) lacks this premise and is heuristic whatever the rule's certainty; the proven reports are the rule's exact tier.
Not part of the claim: how many times the statement runs (one under a branch inside the loop
counts), and how large the loop or the container is. The message claims no size and no cost
estimate. A loop or a container that the code fixes at 16 or fewer items is not reported, since the
rewrite would not pay off. The exact tier also asks that the data decide how many times the loop
runs: the loop steps through a parameter (*args included) or a part of one, the rows of a query,
the lines of a file, or the entries of a directory, as EFF103's Origin establishes them, and the
code does not fix or cap their number. A proven report over any other loop is heuristic, for example
over a loop whose trip count the code fixes at more than 16 or caps with a length test every path to
the loop passes, over the program's structure (an attribute of self, a project function's result,
range of a configured number, a class's MRO, a module-level list), or in a while loop. Such a
report is true, but its loop usually runs a few times, however large the input.
The rewrite also needs what the container is built from to stay the same during the loop
(ValueLoopInvariant), which only a proven report establishes.
Why is this bad?¶
The container is rebuilt from scratch on every iteration, which costs as much as the scan it was meant to avoid.
Example¶
def matches(items: list[int], keys: list[int]) -> int:
hits = 0
for i in items:
if i in set(keys):
hits += 1
return hits
Use instead:
def matches(items: list[int], keys: list[int]) -> int:
keys_set = set(keys)
hits = 0
for i in items:
if i in keys_set:
hits += 1
return hits
Fix safety¶
Proven safe only when the rebuilt expression is a builtin constructor without side effects,
every value it reads is bound outside the loop and not changed inside it, and building it before
the loop cannot raise even when the loop runs zero times (hashable builtin elements). The
container must be used by the membership test only: (tmp := list(keys)) followed by
tmp.clear() would clear the one shared container. Calls with * arguments (list(*args)
passes the elements of args) and method calls with arguments are not hoisted.
Not reported when the loop runs a fixed small number of times, when the rebuilt container is
small whatever the input (set(paths[:2]), tuple(".;:")), or when nothing is rebuilt:
tuple(t) of a tuple returns t itself.