optimize foreach