Optimize the loops and functions within the loops.