Fixed some performance and memory leaks