Substitute Algorithm Dart Example: Faster Swaps That Work

The substitute algorithm Dart example that matters: replace a slow implementation with a simpler one that produces identical results — a nested loop becomes a Set lookup, measured with a stopwatch.

Substitute Algorithm means replacing a complicated or slow implementation with a simpler one that produces the same observable results. This substitute algorithm Dart example shows the classic swap: a nested-loop membership check becomes a Set lookup — identical answers, O(n²) down to O(n). The safety rule: pin the behavior with a test first, then swap, then measure. The Rule Before You Swap: Pin Behavior, Then Substitute Fowler lists Substitute Algorithm as a *composing methods* refactoring, and the mechanics are deliberately boring: Pin the behavior. Write a test (or at least an assertion) capturing the current implementation&#x27;s observable results on representative inputs. Substitute. Replace the body with the simpler algorithm. Measure. Benchmark before and after on realistic data. If it is not faster or not simpler, revert. Step 1 is what separates Substitute Algorithm from "I rewrote it and it seems fine." Without the pin, you cannot tell a successful substitution from an accidental behavior change. If you are unsure how to profile first, our debugging strategies guide covers measuring before you optimize. Substitute Algorithm Dart Example: Nested Loop → Set Lookup One complete runnable Dart 3.10 snippet — the pin, the swap, and the measurement: // BEFORE: O(n*m) — every item in `a` scans all of `b`. bool hasAnyOverlapBefore(List<String> a, List<String> b) { for (final x in a) { for (final y in b) { if (x == y) return true; } } return false; } // AFTER: O(n+m) — build a Set once, then O(1) lookups. bool hasAnyOverlap(List<String> a, List<String> b) { final lookup = b.toSet(); for (final x in a) { if (lookup.contains(x)) return true; } return false; } void main() { final a = List.generate(20000, (i) => &#x27;item-$i&#x27;); final b = List.generate(20000, (i) =>…

Explore