Optimized function call inside foreach