Code taking long time to execute

Have a look here for optimization analysis steps