Hoist this logic out of the loop, since it's used after the end of the loop
Merge pull request #1551 from alex/hoist-from-loop

Hoist this logic out of the loop, since it's used after the end of the loop