Cache for loop lengths

The `length`s never change in the course of their respective functions and so caching them is an appropriate optimization