Cleanup and memory efficiency fix