Improved memory cleanup