Optimized for loops

Length is calculated once rather than on every iteration.