Optimization: use references in loops to prevent copying