Avoid function usage in loops

Complete the previous pull request #5815.