Improved code for better performance of application memory and cpu usage.