Improved the for loops by caching the total length

Improved the for loops by caching the total length, avoiding the call of length method with every iteration.
Should improve performance.