Performance optimization and refactoring