Refactoring code for efficiency