Optimize compare loop