Optimize loop by caching length property