Replace some expensive seq operations with a loop