Skip to content

Loop-Invariant Hoisting

Function calls inside loop bodies that don't depend on the loop variable — the result is the same on every iteration.

Rule details

Rule ID loop-invariant-hoisting
Severity INFO — worth knowing, may not matter at your scale
Confidence LOW — heuristic, check manually
Category Redundancy
Complexity O(n × call) → O(call)

What it detects

for (Item item : items) {
    String timeout = config.getTimeout();  // same result every iteration
    item.apply(timeout);
}

config.getTimeout() doesn't reference item or any variable declared inside the loop.

What it skips

  • Calls that reference the loop variable or any loop-local variable
  • IO methods (side effects)
  • Mutation methods, builder methods, cheap/trivial methods
  • Object constructors (caught by expensive-construction)

Fix

String timeout = config.getTimeout();
for (Item item : items) {
    item.apply(timeout);
}