Optimized foreach loop