Replaced a foreach with a while loop, sprinkled in some final declarations.

We need continuous performance testing. Considering using the
ScalaBlitz optimize.