performance refactor, cache length in loops