Optimise for loops

Cache the length value, since calling length on an array actually causes a lookup. A minor speed improvement.