optimize on several for loops