Fix a memory leak and add a performance improvement