Optimize loop (thanks to cand)