Optimized double loop.