Code optimization: memory allocation and free moved outside of loop.