Refactoring to move function creation out of loops