Fix memory leak and possible performance hit