Optimizing some code to improve performance

Optimizing some code to improve performance