fix memory leak and performance issue