Improve performance by using two loops.