Memory leak bugfix that is also a nice optimization.