Fix memory and performance issue