Refactoring loop handling for better performance