AFAIK the code between parens in the foreach statement is executed just once to obtain a list over which to iterate. So yours is not really an optimization. Update: i see now your and suaveant point as the inner loop get called multiple times: the original post was not that clear.