refactor code, reduce the loop times