Performance improvements and refactoring