optimize several loops (remove use of inject)