Introduction
Loops often repeat the same calculations many times, which wastes time. Finding parts of the loop that do not change and moving them outside can make programs run faster and use less power.
Imagine packing for a trip where you need to fold your clothes every day. If some clothes don't change, like your shoes, you pack them once before the trip instead of folding them daily. This saves time and effort during the trip.
┌───────────────────────────────┐ │ Loop Start │ ├───────────────────────────────┤ │ [Invariant Code] │ ← Moved outside loop ├───────────────────────────────┤ │ Loop Body: │ │ - Code that changes each │ │ iteration │ └───────────────────────────────┘
def compute_sum(arr, n): total = 0 factor = 2 * 3 # Invariant calculation for i in range(n): total += arr[i] * factor return total # Optimized version with invariant code motion def compute_sum_optimized(arr, n): total = 0 factor = 2 * 3 # Moved outside the loop for i in range(n): total += arr[i] * factor return total arr = [1, 2, 3, 4] print(compute_sum(arr, len(arr))) print(compute_sum_optimized(arr, len(arr)))