Optimize loop and lookup