Memory optimizations and refactoring.