further refactoring to improve performance