Loop optimization

Optimized the loop so that the array length is only looked up once, rather than on each iteration.