Rearrange a loop to try to speed it up.