loop function optimization