Performance Boundaries
Loop Bound
Stop Work Early
Performance work starts by bounding how much work a loop can do. A clear limit keeps a script from processing more rows than the caller intended.
Program
Play the script to choose the loop limit and see how many items are processed.
loop_bound_plan.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash
limit=3
count=0
for i in 1 2 3 4 5; do
if [[ "$i" -gt "$limit" ]]; then
break
fi
count=$((count + 1))
done
echo "processed=$count limit=$limit"
#!/usr/bin/env bash
limit=5
count=0
for i in 1 2 3 4 5; do
if [[ "$i" -gt "$limit" ]]; then
break
fi
count=$((count + 1))
done
echo "processed=$count limit=$limit"
limit ← 3
3limit=34count=0values this step3limitcount ← 0
3limit=34count=05for i in 1 2 3 4 5; dovalues this step0countcount ← 1
8 fi9 count=$((count + 1))10donevalues this step0 → 1count1icount ← 2
8 fi9 count=$((count + 1))10donevalues this step1 → 2count2icount ← 3
8 fi9 count=$((count + 1))10donevalues this step2 → 3count3iif [[ "$i" -gt "$limit" ]]; then
5for i in 1 2 3 4 5; do6 if [[ "$i" -gt "$limit" ]]; then7 breakvalues this step4i3limit3countecho "processed=$count limit=$limit"
10done11echo "processed=$count limit=$limit"outputprocessed=3 limit=3values this step3count3limit
limit ← 5
3limit=54count=0values this step5limitcount ← 0
3limit=54count=05for i in 1 2 3 4 5; dovalues this step0countcount ← 1
8 fi9 count=$((count + 1))10donevalues this step0 → 1count1icount ← 2
8 fi9 count=$((count + 1))10donevalues this step1 → 2count2icount ← 3
8 fi9 count=$((count + 1))10donevalues this step2 → 3count3icount ← 4
8 fi9 count=$((count + 1))10donevalues this step3 → 4count4icount ← 5
8 fi9 count=$((count + 1))10donevalues this step4 → 5count5iecho "processed=$count limit=$limit"
10done11echo "processed=$count limit=$limit"outputprocessed=5 limit=5values this step5count5limit
loop bound
A loop bound limits how many iterations a script can perform.
early stop
`break` exits the loop once the boundary is reached.
work count
Counting processed items makes the boundary visible in output.