Optimize inner loop