Improve code performance in for-loop