Fix bad performance in loop

Don't call periods.length every time we compare i with periods.length.
Make other small performance improvements.