Moved length checks outside of loop.

When a loop runs, the check gets processed each time. Since the length of these loops are not changing, checking their length each time is unnecessary. This allows us to assign a variable that stores the length we will check against.