Performance-Aware Loops
Early Exit Scan
Stop When Found
An early exit can reduce unnecessary loop work when a condition has already been satisfied.
Program
Play the program to choose the target and compare how many checks the scan performs.
early_exit_scan.f90
program early_exit_scan_demo
implicit none
integer :: values(5)
integer :: target
integer :: i
integer :: checks
integer :: found_at
values = [3, 6, 9, 12, 15]
target =
checks = 0
found_at = 0
do i = 1, size(values)
checks = checks + 1
if (values(i) == target) then
found_at = i
exit
end if
end do
print '(I0, 1X, I0)', found_at, checks
end program early_exit_scan_demo
program early_exit_scan_demo
implicit none
integer :: values(5)
integer :: target
integer :: i
integer :: checks
integer :: found_at
values = [3, 6, 9, 12, 15]
target =
checks = 0
found_at = 0
do i = 1, size(values)
checks = checks + 1
if (values(i) == target) then
found_at = i
exit
end if
end do
print '(I0, 1X, I0)', found_at, checks
end program early_exit_scan_demo
program early_exit_scan_demo
implicit none
integer :: values(5)
integer :: target
integer :: i
integer :: checks
integer :: found_at
values = [3, 6, 9, 12, 15]
target =
checks = 0
found_at = 0
do i = 1, size(values)
checks = checks + 1
if (values(i) == target) then
found_at = i
exit
end if
end do
print '(I0, 1X, I0)', found_at, checks
end program early_exit_scan_demo
early exit
`exit` leaves the loop as soon as the target is found.
checks
`checks` shows the amount of scanning work performed.
sentinel
`found_at = 0` records the not-found case without raising an error.